For vs While Loop in C
×


For vs While Loop in C

243

For Loop in C 

 The for loop in C is used to execute a block of code repeatedly until a specified condition is met.

 In C, the for loop starts with setting up then checks a condition, and finally changes something each time it runs, lasting until the condition is no longer true.

Syntax of For Loop in C:

		

for (initialization; condition; increment/decrement) { // Code to be executed }

Example:

The sum of Numbers using for Loop:

 // Program for For loop in C
#include<stdio.h> 

int main() {
    int sum = 0, i;
    for (i = 1; i <= 5; ++i) {
        sum += i;
    }
    printf("Sum of numbers from 1 to 5: %d\n", sum);
    return 0;
}	

Output:

Sum of numbers from 1 to 5: 15

While Loop in C 

 The while loop in C is used to execute a block of code repeatedly as long as a specified condition is true.

 Before executing the code block, the loop assesses whether the condition is met.

Syntax of while loop in C:

		

while (condition) { // Code to be executed }

Example:

The sum of Numbers using while Loop:

// Program for while loop
#include<stdio.h>

int main() {
    int sum = 0, i = 1;
    while (i <= 5) {
        sum += i;
        ++i;
    }
    printf("Sum of numbers from 1 to 5: %d\n", sum);
    return 0;
}	

Output:

Sum of numbers from 1 to 5: 15

Both for and while loops serve the purpose of repeating a block of code, and the choice between them depends on the specific requirements of the program and the nature of the iteration.

Difference between For and While loop  

Aspect 
For Loop  
 While Loop
Initialization 
Initialization within the loop
Initialization outside the loop
Condition Check
Checked at the beginning of each loop
Checked at the beginning of each loop
Increment 
Included in the loop 
Excluded from the loop  
 Use Cases  
Definite iterations   
Indefinite iterations 
Statement Format
for (initialization; condition; increment/decrement)
 while (condition)




Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments