Index-1              Index-2              Home Page

Loops in C

How to use Loops in C

In any programming language including C, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

How it Works

The below diagram depicts a loop execution,
loopflow diagram in C
As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false then the execution breaks out of the loop. After the loop is successfully executed the execution again starts from the Loop entry and again checks for the Test condition, and this keeps on repeating.
The sequence of statements to be executed is kept inside the curly braces { } known as the Loop body. After every execution of the loop body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check returns false, the loop body is not executed, and execution breaks out of the loop.

Types of Loop

There are 3 types of Loop in C language, namely:
  1. while loop
  2. for loop
  3. do while loop

while loop

while loop can be addressed as an entry control loop. It is completed in 3 steps.
  • Variable initialization.(e.g int x = 0;)
  • condition(e.g while(x <= 10))
  • Variable increment or decrement ( x++ or x-- or x = x + 2 )
Syntax :
variable initialization;
while(condition)
{
    statements;
    variable increment or decrement; 
}

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )
{
    int x;
    x = 1;
    while(x <= 10)
    {
        printf("%d\t", x);
        /* below statement means, do x = x+1, increment x by 1*/
        x++;
    }
}
1 2 3 4 5 6 7 8 9 10

for loop

for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. We can say it is an open ended loop.. General format is,
for(initialization; condition; increment/decrement)
{
    statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after the condition. In this loop we can have more than one initialization or increment/decrement, separated using comma operator. But it can have only one condition.
The for loop is executed as follows:
  1. It first evaluates the initialization code.
  2. Then it checks the condition expression.
  3. If it is true, it executes the for-loop body.
  4. Then it evaluate the increment/decrement condition and again follows from step 2.
  5. When the condition expression becomes false, it exits the loop.

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )
{
    int x;
    for(x = 1; x <= 10; x++)
    {
        printf("%d\t", x);
    }
}
1 2 3 4 5 6 7 8 9 10

Nested for loop

We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is,
for(initialization; condition; increment/decrement)
{
    for(initialization; condition; increment/decrement)
    {
        statement ;
    }
}

Example: Program to print half Pyramid of numbers

#include<stdio.h>

void main( )
{
    int i, j;
    /* first for loop */
    for(i = 1; i < 5; i++)
    {
        printf("\n");
        /* second for loop inside the first */
        for(j = i; j > 0; j--)
        {
            printf("%d", j);
        }
    }
}
1 21 321 4321 54321

do while loop

In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement. It means that the body of the loop will be executed at least once, even though the starting condition inside while is initialized to be false. General syntax is,
do
{
    .....
    .....
}
while(condition)

Example: Program to print first 10 multiples of 5.

#include<stdio.h>

void main()
{
    int a, i;
    a = 5;
    i = 1;
    do
    {
        printf("%d\t", a*i);
        i++;
    } 
    while(i <= 10);
}
5 10 15 20 25 30 35 40 45 50

Jumping Out of Loops

Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becomes true. This is known as jumping out of loop.

1) break statement

When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop.
break statement in loops in c language

2) continue statement

It causes the control to go directly to the test-condition and then continue the loop process. On encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.
continue statement in loops in c language

Operator in C Programming Language

An operator is a symbol which operates on a value or a variable. For example: + is an operator to perform addition.
C has wide range of operators to perform various operations.

C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition, subtraction and multiplication on numerical values (constants and variables).
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division( modulo division)

Example 1: Arithmetic Operators

// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
    int a = 9,b = 4, c;
    
    c = a+b;
    printf("a+b = %d \n",c);

    c = a-b;
    printf("a-b = %d \n",c);
    
    c = a*b;
    printf("a*b = %d \n",c);
    
    c=a/b;
    printf("a/b = %d \n",c);
    
    c=a%b;
    printf("Remainder when a divided by b = %d \n",c);
    
    return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The operators +, - and * computes addition, subtraction and multiplication respectively as you might have expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.
It is because both variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder is 1. The % operator can only be used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,

a/b = 2.5  // Because both operands are floating-point variables
a/d = 2.5  // Because one operand is floating-point variable
c/b = 2.5  // Because one operand is floating-point variable
c/d = 2     // Because both operands are integers

Increment and decrement operators

C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.

Example 2: Increment and Decrement Operators

// C Program to demonstrate the working of increment and decrement operators
#include <stdio.h>
int main()
{
    int a = 10, b = 100;
    float c = 10.5, d = 100.5;

    printf("++a = %d \n", ++a);

    printf("--b = %d \n", --b);

    printf("++c = %f \n", ++c);

    printf("--d = %f \n", --d);

    return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
Here, the operators ++ and -- are used as prefix. These two operators can also be used as postfix like a++ and a--. Visit this page to learn more on how increment and decrement operators work when used as postfix.

C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment operator is =
Operator Example Same as
= a = b a = b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b

Example 3: Assignment Operators

// C Program to demonstrate the working of assignment operators
#include <stdio.h>
int main()
{
    int a = 5, c;

    c = a;
    printf("c = %d \n", c);

    c += a; // c = c+a
    printf("c = %d \n", c);

    c -= a; // c = c-a
    printf("c = %d \n", c);

    c *= a; // c = c*a
    printf("c = %d \n", c);

    c /= a; // c = c/a
    printf("c = %d \n", c);

    c %= a; // c = c%a
    printf("c = %d \n", c);

    return 0;
}
Output
c = 5 
c = 10 
c = 5 
c = 25 
c = 5 
c = 0

C Relational Operators

A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0

Example 4: Relational Operators

// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
    int a = 5, b = 5, c = 10;

    printf("%d == %d = %d \n", a, b, a == b); // true
    printf("%d == %d = %d \n", a, c, a == c); // false

    printf("%d > %d = %d \n", a, b, a > b); //false
    printf("%d > %d = %d \n", a, c, a > c); //false


    printf("%d < %d = %d \n", a, b, a < b); //false
    printf("%d < %d = %d \n", a, c, a < c); //true


    printf("%d != %d = %d \n", a, b, a != b); //false
    printf("%d != %d = %d \n", a, c, a != c); //true


    printf("%d >= %d = %d \n", a, b, a >= b); //true
    printf("%d >= %d = %d \n", a, c, a >= c); //false


    printf("%d <= %d = %d \n", a, b, a <= b); //true
    printf("%d <= %d = %d \n", a, c, a <= c); //true

    return 0;

}
Output
5 == 5 = 1
5 == 10 = 0
5 > 5 = 0
5 > 10 = 0
5 < 5 = 0
5 < 10 = 1
5 != 5 = 0
5 != 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1 

C Logical Operators

An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming.
Operator Meaning of Operator Example
&& Logial AND. True only if all operands are true  If c = 5 and d = 2 then, expression ((c == 5) && (d > 5)) equals to 0.
|| Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression ((c == 5) || (d > 5)) equals to 1.
! Logical NOT. True only if the operand is 0 If c = 5 then, expression ! (c == 5) equals to 0.

Example #5: Logical Operators

// C Program to demonstrate the working of logical operators

#include <stdio.h>
int main()
{
    int a = 5, b = 5, c = 10, result;

    result = (a == b) && (c > b);
    printf("(a == b) && (c > b) equals to %d \n", result);

    result = (a == b) && (c < b);
    printf("(a == b) && (c < b) equals to %d \n", result);

    result = (a == b) || (c < b);
    printf("(a == b) || (c < b) equals to %d \n", result);

    result = (a != b) || (c < b);
    printf("(a != b) || (c < b) equals to %d \n", result);

    result = !(a != b);
    printf("!(a == b) equals to %d \n", result);

    result = !(a == b);
    printf("!(a == b) equals to %d \n", result);

    return 0;
}
Output
(a == b) && (c > b) equals to 1 
(a == b) && (c < b) equals to 0 
(a == b) || (c < b) equals to 1 
(a != b) || (c < b) equals to 0 
!(a != b) equals to 1 
!(a == b) equals to 0 
Explanation of logical operator program
  • (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
  • (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
  • (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
  • (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
  • !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
  • !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

Bitwise Operators

During computation, mathematical operations like: addition, subtraction, addition and division are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Visit bitwise operator in C to learn more.

Other Operators


Comma Operator

Comma operators are used to link related expressions together. For example:
int a, c = 5, d;

The sizeof operator

The sizeof is an unary operator which returns the size of data (constant, variables, array, structure etc).

Example 6: sizeof Operator

#include <stdio.h>
int main()
{
    int a, e[10];
    float b;
    double c;
    char d;
    printf("Size of int=%lu bytes\n",sizeof(a));
    printf("Size of float=%lu bytes\n",sizeof(b));
    printf("Size of double=%lu bytes\n",sizeof(c));
    printf("Size of char=%lu byte\n",sizeof(d));
    printf("Size of integer type array having 10 elements = %lu bytes\n", sizeof(e));
    return 0;
}
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Size of integer type array having 10 elements = 40 bytes

 C Ternary Operator (?:)

Ternary operator is a conditional operator that works on 3 operands.

Conditional Operator Syntax

conditionalExpression ? expression1 : expression2
The conditional operator works as follows:
  • The first expression conditionalExpression is evaluated first. This expression evaluates to 1 if it's true and evaluates to 0 if it's false.
  • If conditionalExpression is true, expression1 is evaluated.
  • If conditionalExpression is false, expression2 is evaluated.

Example 7: C conditional Operator

#include <stdio.h>
int main(){
   char February;
   int days;
   printf("If this year is leap year, enter 1. If not enter any integer: ");
   scanf("%c",&February);

   // If test condition (February == 'l') is true, days equal to 29.
   // If test condition (February =='l') is false, days equal to 28. 
   days = (February == '1') ? 29 : 28;

   printf("Number of days in February = %d",days);
   return 0;
}
Output
If this year is leap year, enter 1. If not enter any integer: 1
Number of days in February = 29

Goto Break and Continue Statement in C


Goto Statement :

  • The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally.
Syntax :
goto label;
where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. Thus the target statement will appear as
label:statement;
Each labeled statement within the function must have a unique label, i.e., no two statement can have the same label.
C – GOTO STATEMENT EXAMPLE PROGRAM :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<stdio.h>
#include<conio.h>
void main()
{
int  number;
clrscr();
printf(www.);
goto x;
y:
printf(“.com”);
goto z;
x:
printf(“cprogramming);
goto y;
z:
printf(.bd);
getch();
}

Output:
www.cprogramming.com.bd

 

C programming break and continue statements



In this tutorial, you will learn about c programming break continue statements. Break and continue statements are used to jump out of the loop and continue looping.

Break and continue statements in c

Till now, we have learned about the looping with which we can repeatedly execute the code such as, for loop and while & do … while loop.
Just think what will you do when you want to jump out of the loop even if the condition is true or continue repeated execution of code skipping some of the parts?
For this C provides break and continue statements. By the help of these statements, we can jump out of loop anytime and able continue looping by skipping some part of the code.

The break statement in C



In any loop break is used to jump out of loop skipping the code below it without caring about the test condition.
It interrupts the flow of the program by breaking the loop and continues the execution of code which is outside the loop.
The common use of break statement is in switch case where it is used to skip remaining part of the code.

How does break statement works?

Structure of Break statement



In while loop
while (test_condition)
{
  statement1;
  if (condition )
     break;
  statement2;
}
In do…while loop
do
{
  statement1;
  if (condition)
     break;
  statement2;
}while (test_condition);
In for loop
for (int-exp; test-exp; update-exp)
{
  statement1;
  if (condition)
     break;
  statement2;
}
Now in above structure, if test_condition is true then the statement1 will be executed and again if the condition is true then the program will encounter break statement which will cause the flow of execution to jump out of loop and statement2 below if statement will be skipped.
Programming Tips
break statement is always used with if statement inside a loop and loop will be terminated whenever break statement is encountered.

Example: C program to take input from the user until he/she enters zero.

#include <stdio.h>
int main ()
{
 int a;
 while (1)
 {
   printf("enter the number:");
   scanf("%d", &a);
   if ( a == 0 )
      break;
  }
 return 0;
}
Explanation
In above program, while is an infinite loop which will be repeated forever and there is no exit from the loop.
So the program will ask for input repeatedly until the user will input 0.
When the user enters zero, the if condition will be true and the compiler will encounter the break statement which will cause the flow of execution to jump out of the loop.

The continue statement in C



Like a break statement, continue statement is also used with if condition inside the loop to alter the flow of control.
When used in whilefor or do...while loop, it skips the remaining statements in the body of that loop and performs the next iteration of the loop.
Unlike break statement, continue statement when encountered doesn’t terminate the loop, rather interrupts a particular iteration.

How continue statement work?

Structure of continue statement

In while loop
while (test_condition)
{
  statement1;
  if (condition )
     continue;
  statement2;
}
In do…while loop
do
{
  statement1;
  if (condition)
     continue;
  statement2;
}while (test_condition);
In for loop
for (int-exp; test-exp; update-exp)
{
  statement1;
  if (condition)
     continue;
  statement2;
}
Explanation
In above structures, if test_condition is true then the continue statement will interrupt the flow of control and block of statement2 will be skipped, however, iteration of the loop will be continued.

Example: C program to print sum of odd numbers between 0 and 10

#include <stdio.h>
int main ()
{
 int a,sum = 0;
 for (a = 0; a < 10; a++)
 {
   
   if ( a % 2 == 0 )
      continue;
  sum = sum + a;
  }
 printf("sum = %d",sum);
 return 0;
}
Output
sum = 25