#include<stdio.h> #define N 50 struct nganxep{ int data[N]; int top; }; //khoi tao void…
- User
#include<stdio.h> #define N 50 struct nganxep{ int data[N]; int top; }; //khoi tao void khoitao(nganxep &s){ s.top=0; } void them(nganxep &s , int x){ if ( s.top == N){ printf("ngan xep day:"); }else{ s.data[s.top] = x; s.top ++; } } int lay(nganxep &s){ if( s.top == 0){ printf("ngan xep rong:"); }else { s.top--; } return s.data[s.top ]; } void nhap(nganxep &s){ int n,x; printf("nhap vao so phan tu cua ngan xep:"); scanf("%d",&n); for ( int i =0 ; i< n ; i++){ scanf("%d",&x); them(s,x); } } void xuat(nganxep &s){ for ( int i=s.top -1 ; i >=0 ; i-- ){ if(s.data[i] %2 ==0) printf("%d ", s.data[i]); } printf("\n"); } void tinh_TP(nganxep &s, int M) { nganxep u; khoitao(u);
if (M == 0) { them(u, 0); } else { while (M > 0) { them(u, M % 2); M = M / 2; } } printf("so nhi phan: "); while (u.top > 0) { printf("%d", lay(u)); } printf("\n");}
int main (){ struct nganxep s; int x,M; khoitao(s); nhap(s); lay(s); xuat(s); printf("nhap vao M:"); scanf("%d",&M); tinh_TP(s,M);
}
- Assistant
This code implements a basic stack (ngan xep in Vietnamese) in C, with several operations such as initializing, pushing (adding), popping (removing) elements, and converting an integer to its binary representation.
Here's a breakdown of the code:
-
Definitions and Initialization:
-
- User
Cho một ngăn xếp chứa tối đa m số nguyên. Viết chương trình thực hiện các yêu cầu sau: Câu 1 (6 điểm)
- Biểu diễn ngăn xếp bởi con trỏ
- Viết hàm nhập dữ liệu cho ngăn xếp
- Viết hàm hiển thị dữ liệu trong ngăn xếp ra màn hình
- Assistant
- User
làm tự như này cho câu 1 ở trên #include<stdio.h> #define N 50 struct nganxep{ int data[N]; int top; }; //khoi tao void khoitao(nganxep &s){ s.top=0; } void them(nganxep &s , int x){ if ( s.top == N){ printf("ngan xep day:"); }else{ s.data[s.top] = x; s.top ++; } } int lay(nganxep &s){ if( s.top == 0){ printf("ngan xep rong:"); }else { s.top--; } return s.data[s.top ]; } void nhap(nganxep &s){ int n,x; printf("nhap vao so phan tu cua ngan xep:"); scanf("%d",&n); for ( int i =0 ; i< n ; i++){ scanf("%d",&x); them(s,x); } } void xuat(nganxep &s){ for ( int i=s.top -1 ; i >=0 ; i-- ){ if(s.data[i] %2 ==0) printf("%d ", s.data[i]); } printf("\n"); } void tinh_TP(nganxep &s, int M) { nganxep u; khoitao(u);
if (M == 0) { them(u, 0); } else { while (M > 0) { them(u, M % 2); M = M / 2; } } printf("so nhi phan: "); while (u.top > 0) { printf("%d", lay(u)); } printf("\n");}
int main (){ struct nganxep s; int x,M; khoitao(s); nhap(s); lay(s); xuat(s); printf("nhap vao M:"); scanf("%d",&M); tinh_TP(s,M);
}
- Assistant