Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Sujith V S
Sujith V S

Posted on • Edited on

     

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 modeExit 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 modeExit 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 modeExit 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 modeExit fullscreen mode

Example:

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

for loop

Syntax:

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

Example:

int main() {    for(int i=0; i<10; i++){        printf("%d ", i);    }    return 0;}
Enter fullscreen modeExit 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 modeExit 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 modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

React | Django | ..
  • Joined

More fromSujith V S

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp