Programming C: Posts 7 – WHILE loop, do…while trong C
Content
In the previous post, we became acquainted with the loop with the utility that we repeated several times. This article we continue to learn 2 Other types of loops have similar functionality using loop but there is a little different loop while and do…while.
Are you aware of the websites that we need to sign in? As facebook or google simple. If you write the wrong username or password will not be able to sign despite how many times you enter more. Every wrong is they catch us in again. Obviously in qualifying for we often see a for loop repeat some specific times from 1 to n,… But the log does not know how many times that only new is true, the new ending. That is how the while loop and so…while.
1. WHILE loop
While loop structure
Example 1:
Write a program in any number until it stops enter negative numbers.
#include <stdio.h> int main() { int x = 1; // make x >= 0 is true -> while will run while (x >= 0) { printf("Nhap vao mot so : "); scanf("%d", &x); } printf("Ok, Program is finish!\n"); return 0; }
Noted: Above you just declare just assign a value to the variable x is 1 to ensure that the original while loop conditional right to execute the command inside, then each entry, then enter that's what x received. If not set to start 1 it can x will receive 1 random value and can make the loop sound fails.
Result:
Enter some : 4
Enter some : 5
Enter some : 2
Enter some : 0
Enter some : 1
Enter some : -3
Ok, Program is finish!
Example 2:
Print the numbers 9 about 0 Descending. The number is located on 1 current.
Normally you would think of loop. ok standard. But here I want you to know how to use the while well done.
#include <stdio.h> int main() { int n = 10; while (n--) { printf("%d ", n); } printf("\n"); return 0; }
Very simple. But note a bit of condition in the while loop in the code above is what?
That is the other n 0 or not. when writing while (n--)
ie check other n 0 or not or can be understood as the right n (right are 0) the print job number n. still work n--
then just subtract n 1 alone unit. And an important note in the results:
9 8 7 6 5 4 3 2 1 0
Why 0 still in print while under analysis, when n = 0 ie condition is false, wrong, they must escape rather? It is due to expression n--
our. When n = 1 then n--
will n value 0. But by the expression except in the back n it made after the inspection order n = 0. Ie when n = 1 the expression while(n--)
still correct and then drop the new n 0 and perform the job, so when will print printed numbers 0.
2. Loop…while
Loop structure…while
Example 1
Save before your facebook password. Write a program to enter a password to login.
#include <stdio.h> #include <string.h> // for strcmp function int main() { char p[20] = "Iloveyou"; // pass saved char pass[20]; // pass must enter do { printf("Enter your password: "); gets(pass); } while ( strcmp(p, pass) != 0); printf("Ok. You are login success!\n"); return 0; }
Result:
Enter your password: offices
Enter your password: Nguyen Van agencies
Enter your password: iloveyou
Enter your password: iloveyou
Ok. You are login success!
Noted: In the above code, I have used the function strcmp to compare 2 Chain, This function is located in the library string.h
Strcmp function compares strings and string p pass and gives results:
- 1 If p is greater than the pass
- 0 If p same pass
- -1 If p is less than pass
So we have conditions strcmp(p, pass) != 0
ie 2 This sequence is not identical.
Detailed comparison 2 Chain, your reference at all Compare 2 strings in C – strcmp
3. Compare, using loop, while, do…while
- Loop commonly used to know the number of iterations determined.
- Usually while loop, do…while using the unknown number of iterations
- When calling the while loop, do…while, if the condition is false, while loop will not be performed once, but loop…while realizable 1 time.
Exercise
- Write a program that repeatedly enter a character work and print out the ASCII code of that character, when to enter 0 then stop. ( Refer ASCII encoding )
- Write a program that prints out letters: “Do you love me?”, And for users to enter c (have) or k (not). When entering c, stop program, even if they themselves begin entering reenter k ^^. (Send girlfriend / boyfriend)
- Enter 1 number, analysis of which achievement of the prime factors.
- Write a program to find USCLN, BSCNN of 2 number.
for example in white loop 1 Kids to int x; the program is still running, but why must annotation record for x>= 0 huh
Because variable declaration int x, the value of x will not know in advance, maybe 1 random number that we can not control.
#include
int main ()
{
int x = 1;
printf(“you love me ?\n”);
printf(“1: What n”);
printf(“2: n”);
while(x != 1);
{
printf(“answer: “);
scanf(“%d”, &x);
}
printf(“i love u”);
return 0;
}
al check in giúp … Exercises below k out :3
Initially you assign x = 1 then the condition of the while(x!=1) going wrong, should not be done while loop. You should assign initial values x 1 Others 1.
Kids assigned by others 1 it k run loop is why a right @@
You sent the #include behold. You do not get what the library insert program run. With your back to int x = 0 or something else 1 to new conditions while strictly okay.
After a while no ;
Brother to ask you want to print a print a greeting into 100 hi, use the command while ignoring how ạ
Oh mn of all solutions to cook what sir:>
Recommended: give 2 integer a,b search for the baby and the big(k operator conditions ?: and the IF function )
#include
int main()
{
int a = 0;
do {
printf(” you love me?:Dn”);
printf(“1: What n”);
printf(“2: n”);
printf(“between loi n”);
scanf(“%d”,&the);
}
while (the!=1);
{
printf(“I love you =))”);
}
return 0;
}
I did this there was not a
you funny thiet..cho 2 d.a that k for ngta selected..
#include
int main ()
{
int x;
printf(“Kids love me n”);
printf(“1: What n”);
printf(“2: n”);
while(x!=1)
{
printf(“answer: “);
scanf(“%d”, &x);
}
if(x==1)
printf(“i love u”);
f(x==2)
//printf(“I love velvet m”);
return 0;
}
I use the while loop…This is not due solve sir
Recommended: Enter a string and delete the extra spaces between each word only to 1 spaces
#include
#include
#include
main()
{ int i;
char s[10],*p;
printf(“\n Click on a string “);fflush(stdin);
gets(with);
while(in< strlen(with));
{
i=i++;
if(with[in]==' '&&with[i 1]==' ')
{strcpy(&with[in],&with[i 1]);
i=i–;}
}
puts(with);
}
#include
main()
{
char x;
printf(“Do you love a k n”);
printf(“With or without n”);
while(x!=’c’)
{
printf(“I di tl :”);
scanf(“%c”,&x);
}
printf(“i love you”);
return 0;
}
problem:when entering e k or any other letters c, then print out the lines you go tl 2 East Asia!!!
You see the float command nhé.
#include
#include
int main()
{
printf(“England you love me?\n”);
printf(“1. What n”);
printf(“2. Khong n”);
char p[20] = “Co”;
char pass[20];
do
{
printf(” Anh between the loi: “);
gets(pass);
} while ( strcmp(p, pass) != 0);
printf(“Ok. I love you n”);
return 0;
}
Please ask everyone. Loop that utilize multiple conditions 2 or multivariate sir?
This is up treatment, custom work to do alone.
{
int n;
scanf(“%d”, &n);
printf(“%d = 1 * “,n);
for(int i = 2;in<=n;i ){
while(n%i==0){
printf("%d * ", in);
n /= i;
}
}
return 0;
}
You visit https://code.cachhoc.net to submit nhé.
/*viet chuong trinh nhap vao mot ky tu va in ra ma ascii cua ky tu do*/
#include
#include
#include
int main()
{
char c;
while(c!=’0′)
{
c = getch();
printf(” ma ascii cua %c la: %d \n”, c, c);
}
}
hi vọng ngoài cách dùng c = getch(); như bài của em thì mong ae đóng góp cho em thêm những các khác vì dạng này khi kết hợp với while mà dùng getchar thì em thấy là nó đọc luôn cả enter xuống dòng
Dùng scanf được nhé 🙂 Bạn có thể vào trang https://chamcode.net để làm thêm nhiều bài tập hơn 🙂
cho e hỏi bài tin lớp 8 về pascal với ạ!
use iteration statements with unknown number of times before, to write the program into the finish entering integer numbers 0. calculate and print summary screen just entered integer
sir thanks much
You use the repeat purchase until nhé.
e asked that the program only allows enter two integer and its total import what type ak?
You see it this post: https://cachhoc.net/2018/01/11/lap-trinh-c-bai-3-nhap-xuat-trong-c/#Vi_du_1-2
cho em hỏi bài 3 How sir oriented solutions ?
See here while. https://cachhoc.net/2017/05/31/phan-tich-thua-nguyen/
I asked for directions to do the post of 4 How did he ?
This formula then, you can do.
Posts 4 I see you help me sir you find the greatest common divisor k :((((
#include
int main() {
int a[20] , b [20] , n , m , i = 1 , j = 1 ,d;
printf(“nhap n : “);
scanf(“%d”,&n);
printf(“nhap m : “);
scanf(“%d”,&m);
printf(“n la Convention : “);
while(in <= n/2) {
if(n % i == 0) {
printf("%d ",in);
the[j] = I ;
j ;
}
i ;
}
printf("\nuoc cua m la : ");
i = 1;
j = 1;
while(in <= m/2) {
if(m % i == 0) {
if(m % i == 0) {
printf("%d ",in);
b[j] = I;
j ;
}
}
i ;
}
for(i = 1;in <= 20;i ) {
for(j = 1;j <=20;j ) {
if(the[in] == b[j]){
d = i;
}
}
}
printf("\n %d la ucln",the[d]);
return 0;
}
You can go to website https://chamcode.net to do (Posts 33) to put right the wrong system always, Also based on that adjust code.
He asked me,command to check two conditions . CEO: 0<n<=10
thank ah.
0 < n && n <=10 nhé.
#include
#include
using namespace std;
int main()
{
int n;
do
{
cout<>n;
if (n20)
{
cout<<"\n Gia tri n khong hop le, Please re-enter!";
}
}while (n20);
return 0;
}
star running back at improper conditions sir
Let me ask how to use the do while loop to check the data with. Vid eg enter a positive value. If a<= 0 Re-enter request until satisfied
do {
scanf
}while(the <= 0)
Let me ask you to write C ++ to enter a positive integer k with conditions 0 < to <= 20 by the while loop structure, how about (C )
P/s: C ++, man
while(to < = 0 || k > 20) cin >> k.