#include<stdio.h>
int main()
{
int i=1;
while (i <=5){
printf("%d \n",i); // Output
i=i+1; // increment of i by 1
}
return 0;
}
The above code will give this output.
1
2
3
4
5
#include<stdio.h>
int main()
{
int i=1;
while (i <=5){
printf("%d \n",i); // Output
}
return 0;
}
Sometime even the increment conditions became in such a way that the condition never became false and it became indefinite loop.
#include<stdio.h>
int main()
{
int i=1;
while (i <=5){
printf("%d \n",i); // Output
i=i-1; // decrement of i by 1
}
return 0;
}
#include <stdio.h>
int main(void){
int i=1;
while(i <= 5){
printf("\n I value before increment : %d ", i);
i=i+1; // increment of i by 1
if(i==4){
break;
}
printf("\n I value after increment : %d ", i);
}
return 0;
}
Output is here
I value before increment : 1
I value after increment : 2
I value before increment : 2
I value after increment : 3
I value before increment : 3
Note that i value 4 and i value 5 is not printed as break; statement stopped the execution of the loop.
while(i <= 5){
printf("\n I value before increment : %d ", i);
i=i+1; // increment of i by 1
if(i==4){
continue;
}
printf("\n I value after increment : %d ", i);
}
Output
I value before increment : 1
I value after increment : 2
I value before increment : 2
I value after increment : 3
I value before increment : 3
I value before increment : 4
I value after increment : 5
I value before increment : 5
I value after increment : 6
Note that one step is skiped. The step to show I value after increment : 4
is not displayed ( skipped ) but execution continued from staring of the loop again and displayed next value.
i++; // increment i value by 1
i--; // decrement i value by 1
i += 5; // increment i value by 5
i -= 5; // Decrement i value by 5
#include<stdio.h>
int main()
{
int i=50;
while (i >= 0){
printf("%d \n",i); // Output
i-=10; // increment of i by 1
}
return 0;
}
Output is here
50
40
30
20
10
0
#include<stdio.h>
#include<string.h>
int main()
{
char str[30]="plus2net";
int str_length;
str_length=strlen(str); // length of the string
while(str_length>=0){
printf("%c",str[str_length]);
str_length--;
}
return 0;
}
#include <stdio.h>
int main() {
int sum = 0, i = 1;
while (i <= 5) {
sum += i;
i++;
}
printf("Sum: %d\n", sum);
return 0;
}
#include <stdio.h>
int main() {
int number;
printf("Enter a number between 1 and 10: ");
scanf("%d", &number);
while (number < 1 || number > 10) {
printf("Invalid input. Please enter a number between 1 and 10: ");
scanf("%d", &number);
}
printf("You entered a valid number: %d\n", number);
return 0;
}
21-01-2020 | |
Write a program that finds the sum of even numbers between zero and twenty use while loop |