DEV Community

Sujith V S
Sujith V S

Posted on • Edited on

3 1 1 1 1

Loops in C programming

In C programming there are 3 types of loop and they are while loop, for loop and do while loop.

While loop

In while loop the body is executed until the test condition become false.
Syntax:

while (conditiuon){
    //statement inside while.
}
Enter fullscreen mode Exit fullscreen mode

Example:

#include <stdio.h>
int main() {
    int count = 1;

    while (count < 5){
        printf("While loop in c\n");
        count = count + 1;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Multiplication table using while loop:

#include <stdio.h>

int main() {
    int number;
    printf("Enter the number: ");
    scanf("%d", &number);

    int count = 1;
    while(count <= 10){
        int product = number * count;
        printf("%d x %d = %d \n", count, number, product);
        count = count + 1;
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

do while loop

Here the body of the loop is executed and then the condition is evaluated, if the condition is true the body of the loop is executed again.
syntax:

do {
  //body of loop
  } while(condition);
Enter fullscreen mode Exit fullscreen mode

Example:

int main(){

    int count = 5;

    do{
        printf("%d\n", count);
        count = count + 1;
    } while(count < 5);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

for loop

Syntax:

for(initializationExpression; testExpression; updateExpression){
//codee inside for loop.
}
Enter fullscreen mode Exit fullscreen mode

Example:

int main() {

    for(int i=0; i<10; i++){
        printf("%d ", i);
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Sum of whole numbers from 1 to 100:

int main() {
    int sum=0;

    for(int i=1; i<=100; i++){
        sum=sum+i;

    }
    printf("%d", sum);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Sum of even numbers:

int main() {
    int sum=0;

    for(int i=2; i<=100; i=i+2){
        sum=sum+i;
    }

    printf("%d", sum);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay