Programming C: Posts 9 – Arrays in C
Content
Before learning about the array in C, we try to do for example the opening.
1. For example, the opening
Consider the example entry 5 integer, output to the screen 5 Among them on a line and total 5 which.
// e.g about array - code by nguyenvanquan7826 #include <stdio.h> int main() { int a, b, c, d, e; // 5 bien printf("Nhap a = "); scanf("%d", &a); printf("Nhap b = "); scanf("%d", &b); printf("Nhap c = "); scanf("%d", &c); printf("Nhap d = "); scanf("%d", &d); printf("Nhap e = "); scanf("%d", &e); int tong = a + b + c + d + e; printf("Tong cua %d + %d + %d + %d + %d = %d \n", a, b, c, d, e, tong); return 0; }
Result:
Nhap a = 3
Nhap b = 5
Nhap c = 3
Nhap d = 6
Nhap e = 1
Tong crab 3 + 5 + 3 + 6 + 1 = 18
As examples we see entering all 5 and we made some screen seems very hard and we had to use too many variables, if the number of variables that we are not 5 that is 50, 500,... Then this result is very difficult. To remedy this we use the array.
A set of array elements with the same type of data. Array of arrays 1 evening, 2 evening,... And each type of data, there 1 corresponding array (integer array, real array, character array (Chain)),... I mainly consider the array 1 dimensional array 2 evening.
Now we will solve the examples on using arrays 1 evening.
2. Arrays 1 evening
2.1 Example overview
Have you tried to read and run this program, then please see details below.
// e.g about array - code by nguyenvanquan7826 #include <stdio.h> int main() { // khai bao mang a co n phan tu int n = 5, i, s = 0; int a[n]; // thuc hien nhap tung phan tu mang for (i = 0; i < n; i++) { printf("Nhap a[%d] = ", i); scanf("%d", &a[i]); } // thuc hien in cac phan tu cua mang ra man hinh printf("\nMang da nhap \n"); for (i = 0; i < n; i++) { printf ("%d \t", a[i]); } // tinh tong cac so trong mang for (i = 0; i < n; i++) { s += a[i]; // s = s + a[i] } printf("\nTong cac so trong mang: %d\n", s); return 0; }
Import a[0] = 3
Import a[1] = 4
Import a[2] = 6
Import a[3] = 2
Import a[4] = 7
Bring entered
3 4 6 2 7
Sum of the carrying: 22
2.2 How to declare array 1 evening
KieuDuLieu TenMang [SoPhanTu];
CEO: int a[10];
Arrays 1 afternoon included a 10 elements of type integer. After declaring have 1 array looks like this:
2.3 How to access elements in the array
After the array is declared, each element in the array are for reference index. The index starts from 0 to n-1 (where n is the size of the array). In the above example, I declare array 10 element, the index starting 0 to 9.
And we accessed via syntax: TenMang[ChiSo]
2.4 How to import and export the elements of the array
To enter data for the elements in the array we need to browse to each element in the array and proceed to enter a loop
for (i = 0; i < n; i++) { printf("Nhap a[%d] = ", i); scanf("%d", &a[i]); }
The publication of the elements in the array are also conducted similar:
for (i = 0; i < n; i++) { printf ("%d \t", a[i]); }
2.5 Enter output array using function
In many problem, we have to enter multiple arrays, and output multiple times, Meanwhile let's put on a function for easy entry and use.
// e.g about array - code by nguyenvanquan7826 #include <stdio.h> void nhapMang(int a[], int n) { int i; // thuc hien nhap tung phan tu mang for (i = 0; i < n; i++) { printf("Nhap a[%d] = ", i); scanf("%d", &a[i]); } } void xuatMang(int a[], int n) { int i; for (i = 0; i < n; i++) { printf ("%d \t", a[i]); } } int main() { // khai bao mang a co n phan tu int n = 5; int a[n]; nhapMang(a, n); xuatMang(a, n); return 0; }
Noted: An array of relationships with 1 pointer, array so as 1 pointer to the array passed to the function, the elements of the array will be affected if there are any changes in the array.
2.6 A few other notes
Initialize the array: We can initialize the array in the declaration immediately. CEO: float a [5] = {3.4, 5, 6, 7, 4,2}
With this initialization if we initialize exceed 5 element will report an error, without any element is the element that is the value 0.
CEO: float a [5] = {3.4, 5, 7} => a[4] = 0
.
CEO: float a [5] = {3.4, 5, 7, 1, 2, 3}
=> Machine error.
Also we have to declare and initialize a previously unknown number of array.
CEO: int a[] = {3,6,2,5}
=> Array with 4 receiving element corresponding values.
Or: int a[];
=> Often used when using arrays as parameters in function form.
3. Arrays 2 evening
We can consider it as a matrix. The nature, declaring, Import-Export,... Similar array 1 evening.
KieuDuLieu TenMang [SoHang][SoCot];
VD report: int a[5][10];
=> Array a composed 5 goods and 10 post (each row 10 element).
// e.g about array - code by nguyenvanquan7826 #include <stdio.h> #define MAX 10 // nhap mang n hang, m cot void nhapMang(int a[MAX][MAX], int n, int m) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("Nhap a[%d][%d] = ", i, j); scanf("%d", &a[i][j]); } } } // xuat mang n hang, m cot void xuatMang(int a[MAX][MAX], int n, int m) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf ("%-3d", a[i][j]); } printf("\n"); // xuong dong khi het 1 dong } } int main() { // khai bao mang a co n phan tu int n = 2, m = 3; int a[MAX][MAX]; nhapMang(a, n, m); xuatMang(a, n, m); return 0; }
Attention: The essence of memory, the elements of the array 2 evening (and multidimensional arrays) be held as many arrays 1 dimensional consecutive, so we may provide arrays 2 dimensional plaque 1 evening.
chap9-luu-tru-bear-2-pm-in-c.png
Exercise
- Enter into an array, find the biggest and the smallest number in the array entered.
- Enter a series of numbers, print out the location of the largest (can have multiple locations).
- Enter a sequence of precipitation is consecutive month in year. The notice of the May rainfall than the average rainfall of the month.
- Enter a series of numbers, sorted and printed in ascending sequence.
- Entered into a matrix (Plate 2 evening). Print out the sum of each row of the matrix.
Waiter, he asked me as int main void main and different place was?, and the use of int main void main and what's the difference was? ?
Thank you.
void main, the main function returns no value
int main, the main function returns integer values. and we must return a value 0 (ie no error) if returns other values are treated as program errors (provisions examiner olympic).
And to this point is to use the standard provisions nhé int main.
If I do not return records 0; What problems does it not, sir ?
and all his public is also used int main ạ ? (I saw him at the user reads void main,Using int paragraph should have any questions, sir )
No return 0 okay, the program is still running. Make time for yourself unknown void the law.
Then take the exam, it should know int. 🙂
Waiter asked me is the element of the array is stored where, sir ?(FRAME,…)
Why do you declare dragon A[1000000000] the normal translation, even when running it return 3 several billion ?
This is due to a buffer overflow somehow. Rather a declaration has not tried to lead this element. =))
Cho e hỏi là nhập n trong hàm nhập mảng khác nhập n ngoài hàm nhập mảng như nào ạ. Và khi nào thì nhập trong khi nào nhập ngoài ạ
Nhập trong là nhập trong, còn nhập ngoài là nhập ngoài. Khi nào cần truyền n từ ngoài vào thì dùng nhập ngoài.
Waiter, How come you coppy examples 2 its error in nhapMang(the, n, m); is why Bro.
How you specific error?
31 21 C:\UsersTraMy-DangDocumentsmang_hai_chieu.cpp [Error] cannot convert ‘int (*)[(((sizetyp to)(((ssizetype)m) + -1)) + 1)]’ to ‘int (*)[10]’ for argument ‘1’ to ‘void xuatMang(int (*)[10], int, int)’ here.
oh, But his run was okay, delicious…
yes darling…its array error in entering his passage .
The code on any software you so? But his run was okay.
em chay tren dev,visual that are engaged in that darling.
Thank you, I've updated the nhé.
a pdf file k has ạ? k home network, looking also suffering too.
I do not have the pdf file. When you're online, you can press Ctrl + S to save the page as is.
Can you show me how stars can import files array by ko sir
I see this way or use,but I do not know how to open DC ( such as notepad to enter text etc.…)
You find ways to read files in C / C ++ nhé. Then enter the number or anything like keyboard alone.
My brother asked me printf (“%-3d”, the[in][j]); the% -3d mean, what was?.
%Export information xd integers and let x represent blanks, a negative sign to the left flat.
For details, see this post offline.
https://www.cachhoc.net/2014/12/04/lap-trinh-c-bai-2-kieu-du-lieu-va-nhap-xuat-trong-c/#2_Xuat_du_lieu_printf
thank you sir
Em muốn nhờ anh chút ạ
Em có mảng 2 chiều ={xyDfdfgf
………….}
Làm thế nào để thay thế được kí tự x bằng kí tự y trong toàn mảng,còn nhiều hàng khác nữa và em muốn thay thế hai kí tự đầu mỗi hàng như x với y ấy ạ !
Thanks!
Bạn duyệt mảng và so sanha bình thường thôi …
Chào Quân,
Cảm ơn Q vì bài giảng trên.
I want to ask is where you want to create 1 array to hold 1 integer 100 then how digit huh Q ?
Thank Q more.
So you just create arrays 100 element to contain 100 number. However, when calculated, you need to learn how to count large numbers.
Thank Q offline
#include
int main()
{
int n,in;
printf(“Enter the number of rows”);
scanf(“\t% d”,&n);
int a[n]=0;
while (in < n)
{
printf("nhap a[%d]\t",in);
scanf("% D", &the[in]);
}
printf("");
return 0;
}
Why this ct e z a fault running bj
You describe how wrong, but wrong place. Q How did I know.
you should order for replacement while, also like that is wrong due to lack of i ++ in {} already
e asked #define MAX 10 means stars sir
That means constant declarations MAX has value 10
Waiter how to enter into an array that print screen 1 horizontal line immediately after entering sir
Bạn nhập các số tách nhau bằng dấu cách là được 🙂
My friend asked what their. LED blink control his UNO.
for (i=0;in<n;i ) {digitalWrite(The[in],HIGH); digitalWrite(The[i-1],LOW); delay(200); };
When i = 0. The[0] HIGH, but i-1 = -1 <0 the array does not recognize the value or it can choose any 1 element in the array like. Minhg thanks
you i run from 1 is. or constraints of conditions if i> 0 then write a new[i-1]
If i = 1, the A[0] k DC blink, particular attention must write down =]]. Thank you offline,
#include
void input(int a[], int n)
{
int i;
printf(“Input Array:\n”);
for(i=0;in<n;i )
{
printf("a[%d]=", in);
scanf("% D", &the[in]);
}
}
void output(int a[], int n)
{
int i;
printf("Output Array:\n");
for(i=0;in<n;i )
{
printf("%-3d", the[in]);
}
}
int main()
{
int n, in, the[n];
printf("n="); scanf("% D", &n);
input(the, n);
output(the, n);
return 0;
}
He asked me how this code does wrong place, n = 8, then entering Segmetation fault sir @@ error
Incorrect because a declared array[n] before n value.
e ask why e network entry 1 dimensional 10 Molecular error, the machine does not work sir. Finish typing is not output to make is always sir !
#include
void nhapmang(int a[],int n)
{
int i;
for(i=0;in<n;i )
{
printf("nhap a[%d] ",in);scanf("% D",&the[in]);
}
}
int main()
{
int n,max=0,i=0;
printf("nhap n");scanf("% D",&n);
int a[n];
nhapmang(the,n);
for(i=0;in<n;i )
{ if(max<the[in]) max=a[in];
}
printf("% D",max);
for(i=0;in<n;i ){
if(the[in]=max)printf("%i");
else printf("*");
}
}
cousin nhowfvoiws a.tai stars when I run n im out all the positions so ah
Compare you must use == rather than = nhé.
oi a phan 2.1 declare i chi loan
To use it in a for loop i.
#include
int main(){
int m[5],in,trungbinh = 0;
for(i=0;in<5;i ){
printf("nhap m[%d]",in);
scanf("% D",&m[in]);
}for(i=0;in<5;i ){
trungbinh =(trungbinh+m[in])/5;
} printf("% D",trungbinh);
}
for t ask why when t RUN results 0 borrow
data storage array 1 evening, when was calculated automatically
CEO: S1=2, s2=9,…….,Sn=n
save the values in the array, how sir ..??
His thanks
You assign values to the array that is being.
namespace mangmotchieu
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void btnhap_Click(object sender, EventArgs e)
{
int n;
int[] The;
{
n = int.Parse(txtnhapn.Text);
A = new int[n + 1];
for (int i = 0; in < n; i )
{
The[in] = int.Parse(Microsoft.VisualBasic.Interaction.InputBox("nhập phan tử thứ" + (in + 1).ToString()));
txtketqua.Text = txtketqua.Text + " " + The[in].ToString();
}
{
A = new int[n + 1];
for (int i = 0; in 0)
{
btnhap.Enabled = false;
txtketqua.Enabled = true;
}
else
{ MessageBox.Show(“n enter must be a positive integer”); }
{
txtnhapn.Text = “”;
txtnhapn.Focus();
}
}
everyone please help me write the program f voi.khi test positive integer in the array when the program section vegetarian does not enter button
darling comparison and arrangement of elements in the array, why sir
Did you at?? Compare and sort it any severance arrangement, even if not yet know how to do, then you can see here: https://vi.wikipedia.org/wiki/S%E1%BA%AFp_x%E1%BA%BFp_n%E1%BB%95i_b%E1%BB%8Dt#Vi%E1%BA%BFt_b%E1%BA%B1ng_C++
#include
int main()
{ int n;
int a[n];
int max;
printf(“Nhap may so: “);
scanf(“%d”,&n);
for(int i=1;ii)
{
max=a[in];
}
if(the[in]>in)
{
max=a[in];
}
}
printf(“%d”, max);
return 0;
}
ct find the largest number that darling, why did you do that just found the wrong wrong, which results in a still right, hope you see the code and explain to you sir
wrong priest gently. Enter n number, the number that must be entered from the keyboard, you have to enter from the keyboard where. Here tested. https://chamcode.net
#include
int main()
{ int n,in;
int a[20];
int max=0;
int min = 1;
printf(“Nhap may so: “);
scanf(“%d”,&n);
for( i=1;in<=n;i )
{ printf("Nhap so thu %d: ",in);
scanf("% D", &the[in]);
}
for(i=1;in<=n;i )
{
if(max=a[in])
{
min =[in];
}
}
printf(“%d %d”, max, me);
return 0;
}
only he, see this article ne, Now you enter a negative number on it on the max 0 miết darling, only children with, I declare max = 0; even if declared max = 1 others wrong
The initial max = 0 already, re-enter all negative, do have larger number max again. should assign max = the first number after entering and then look.
Articles of a very easy to understand. see on youtube but the whole concept, Done not understand.
a me ask 2 place in all :
1.void nhapMang(int a[MAX][MAX], int n, int m) This is why the MAX MAX without blank as void nhapMang(int a[], int n),MAX is something sir.
2.float a [5] = {3.4, 5, 7} => the[4] = A[5] = 0 This is a[4]=7 a[5]= 0, but why a[4]=a[5].
Plate 2 way, there should be the maximum number of arrays, MAX is the maximum number. Arrays 1 way there is no need.
CEO: float a [5] = {3.4, 5, 7} => A[4] = A[5] = 0. second element means 4 and th 5 = 0 for declarations only from 0 to 3 but.
E is not yet quite understand sir. So array a[5] have to 6 element for adjectives 0 to 5 sir ( There are a total 6 number in brackets).
But why do I have a great number of elements equal to the number the number in brackets as on a record
CEO: int a[] = {3,6,2,5} => array 4 receiving element corresponding values.
Of, sorry you, a little bug here, ie only a[4] = 0 stop, not have a[5], only from a[0] to a[4] because the array declaration 5 element, and initialize the initial 4 shuttle, the end, it is not initialized 0.
#include
int main(){
int n;
printf(“\nNhap so luong phan tu n = “);
scanf(“%d”, &n);
int a[n];
for(int i = 0; in < n; i ){
printf("\nNhap a[%d] = ",in);
scanf("% D", &the[in]);
}
int tg;
int max;
max=n*(A-1)/2;
printf("max %d ",max);
for(int i=0 ;in<max;i ){
for(int j=i+1;j a[j]){
tg = a[in];
the[in] = A[j];
the[j] = tg;
}
}
}
printf(“\nMang da sap xep la: “);
for(int i = 0; in <n; i ){
printf("%5d", the[in]);
}
return 0;
}
Teacher, I arrange from child to adult, Enter n = 1,2,3,4 and still be delicious 5 bigger numbers are wrong ?
This ring has a problem with this.”for(int j=i+1;j a[j]){“
Waiter, where to declare the array a[n] it fails forever a, I can not tell the user to enter something!
Let me ask if there is a way for the user to enter the number of elements directly for the array a?
Enter finished and then declare e.
May I ask when is the time between void main and int main???
Use any one okay, but now they use int.
Can I ask if my school teaches arrays before functions, but I see that all websites teach functions before arrays like that?
It's okay.