Loops in C program
Do while loop in c program
//do while loop
// Do while loops are used when we have to execute block of loop
// at least once for sure i.e. even the condition is false then also
// do while loop get executed for once.
// In do while loop, first of all the statements of do block get
// executed and then the condition is checked and if the condition is true
// then it repeat the same step i.e. control goes to top of the loop
// and again executes it and this process occur till the condition becomes false.
#include <stdio.h>
int main()
{
int num, index = 0;
printf("Enter a number\n");
scanf("%d", &num);
do
{
// In this case we take integer input from user as num
//Then the other integer index perform the program
// Mainly it print the numbers in the order
//untill the index is less than num it will be rotated in the loop
printf("%d\n", index + 1);
index = index + 1;
} while (index < num);
return 0;
}
While loop in c
// While loop is executed only when given condition is true. Whereas,
// do-while loop is executed for first time irrespective of the condition.
// After executing while loop for first time, then condition is checked
#include <stdio.h>
int main()
{
int j = 0, i;
printf("Enter number\n");
scanf("%d", i);
while (i < j)
{
printf("%d\n", j + 1);
j = j + 1;
}
return 0;
}
// In while loop first of all the condition is checked and if it is true then it’s statements
// get executed otherwise it skip the whole while loop block if the condition is failed to satisfy
// In while loop, a condition is checked or evaluated before processing a body of the loop.
// If a condition is true then the body of a loop gets executed. After the body of a loop is executed then control of program again goes back at the beginning of the loop,
// and the condition is checked if it is true, the same process is executed until the condition becomes false in loop. Once the condition becomes false, the control goes out of the while loop.
// After exiting the loop,
// the control goes to the statements which are immediately after the loop or statements next to the loop.
// The body of a loop can contain more than one statement. If it contains only one statement,
// then the curly braces {} are not compulsory to use. It is a good practice though to
// use the curly braces even we have a single statement in the body because it reduces the chances of getting an error.
combining if and while loop
#include <stdio.h>
int main()
{
int a, b = 0, c;
printf("Enter the class which you are studying\n");
scanf("%d", &c);
if (c > 18)
{
printf("You can print numbers using programm\n");
printf("Enter the number\n");
scanf("%d", &a);
while (b < a)
{
printf("%d\n", b + 1);
b = b + 1;
}
}
else
{
printf("You want to write the homework manually\n");
}
return 0;
}
// this programm will write home work atomaticaly
Comments
Post a Comment