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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay