#include <stdio.h>
#include <stdlib.h>
// swap 2 value
void swap(int &x,int &y) {
int t = x; x = y; y = t;
}
//to sort number asc
void bubble(int a[], int n) {
int i, j;
//this loop from the first element index to the n-2 element index
for(i = 0; i < n - 1; i ++) {
//this loop from th second index to the lasr index
for(j = i + 1; j < n; j++) {
//if the value at index i > the value of index j then swap
if(a[i] > a[j]) swap(a[i],a[j]);
}
}
}
//to sort number asc
void bubble2(int a[], int n) {
int i, j;
//this loop from the first element index to the n-2 element index
for(i = 0; i < n - 1; i ++) {
//this loop from th second index to the lasr index
for(j = i + 1; j < n; j++) {
//if the value at index i > the value of index j then swap
if(a[i] < a[j]) swap(a[i],a[j]);
}
}
}
int checkNumber(int inputNum, char check) {
//if check is character not '\n' => input is not a number, return 0
if (check != '\n') {
printf("Data type error.\n");
printf("Please enter interger\n");
return 0;
}
//if input number out of required range, return 0
if (inputNum < 1) {
printf("Input number must be in range n > 1.\n");
return 0;
}
//else return 1
return 1;
}
// enter or check input
void input (int array[], int &n) {
char check;
printf("The Program must have interface as below:\n\n");
printf("please enter size of array: ");
// loop until function checkNumber return value valids
do {
scanf("%d",&n);
check = getchar();
fflush(stdin);
}while (checkNumber(n,check) == 0);
//this loop from the first element index to the n-1 element index
for(int i = 0; i < n; i++) {
printf("Enter element[%d]: ",i + 1);
scanf("%d",&array[i]);
check = getchar();
fflush(stdin);
// if function checkArray return value valid i--;
}
}
// print array storted ascending and descending
void ouput (int array[], int n) {
printf("The array sorted in ascending:\n");
bubble(array,n);
for(int i = 0; i < n; i++) {
printf("%d ",array[i]);
}
printf("\n\nThe array sorted in descending:\n");
bubble2(array,n);
for(int i = 0; i < n; i++) {
printf("%d ",array[i]);
}
}
int main () {
//create dynamic array
int *array = (int*)malloc(10*sizeof(int));
int n;
input(array,n);
// resize dynamic memory
array = (int*)realloc(array,n*sizeof(int));
ouput(array,n);
}
Mọi người giải thích hộ mình đoạn code do while với
David_Luu
(David Lưu)
#1
phamdat2
(Phạm Tiến Đạt)
#2
bạn đưa mỗi code, tiêu đề topic không đưa ra được vấn đề bạn cần hỏi thì sao mình biết bạn đang hỏi cái gì ?
phamdat2
(Phạm Tiến Đạt)
#4
do {
scanf("%d",&n);
check = getchar();
fflush(stdin);
}while (checkNumber(n,check) == 0);
vòng lặp do/while sẽ chạy lần đầu cho đến khi gặp điều kiện -> nếu điều kiện đúng -> chạy tiếp ngược lại thoát vòng lặp.
Thế thôi
Vuio
(Vuio)
#5
Bạn để ý dòng comment này của tác giả (ở trước do)
// loop until function checkNumber return value valids
Nó nói là lặp cho đến khi hàm checkNumber trả về giá trị hợp lệ (checkNumber khác 0). Nếu không hợp lệ (checkNumber = 0) thì quay lên nhập lại đến khi nào hợp lệ thì thôi.