Professional Documents
Culture Documents
L14 L5 1DArray
L14 L5 1DArray
Objectives
{ printf(“%d”,arr[i]);
printf(“\t”);}
return 0;
}
2/22/2020 CSE 1001 Department of CSE 8
Initializing one-dimensional array
int number[3] ={0,0,0}; or {0} ;
declares the variable number as an array of size 3
and will assign 0 to each element.
printf(“%d\n”,x[0]); Output:
9
printf(“%d\n”,x[1]);
11
printf(“%d\n”,x[2]); 13
printf(“%d\n”,x[i]);
2/22/2020 CSE 1001 Department of CSE 11
Program to read n elements into an array and
print it int a[10], i, n;
printf("enter no of numbers“); Output:
scanf(“%d”,&n); enter no of numbers
3
printf(“enter n numbers \n”);
enter n numbers
for(i=0;i<n;i++) 9
scanf(“%d\n”,&x[i]); 11
13
Numbers entered are:
printf(“\nNumbers entered are:\n”); 9
for(i=0;i<n;i++) 11
printf(“%d\n”,a[i]); 13
2/22/2020 CSE 1001 Department of CSE 12
Program to add two array elements and store the
corresponding elements sum in another array
int a[10], b[10], c[10],n, m, i;
printf("enter no. of numbers in if(m==n)
first array\n“); {
for(i=0;i<m;i++)
scanf(“%d”,&n);
c[i]=a[i]+b[i];
//first array
for(i=0;i<n;i++) printf(“Sum of given array
scanf(“%d”,&a[i]); elements\n”);
printf("enter no of numbers in
for(i=0;i<n;i++)
second array\n“);
printf(“%d\n”,c[i]);
scanf(“%d”,&m); }
for(i=0;i<m;i++) //second array else
scanf(“%d”,&b[i]); printf("cannot add“);
}
2/22/2020 CSE 1001 Department of CSE 13
Displaying elements of an array in reverse order.
int a[10], n, i;
Example : a[ ]={1, 2, 3, 4, 5}
printf(“Enter values\n“); Enter values
n=5
for(i=0;i<n;i++) 12345
Reverse printing of array
scanf(“%d”,&a[i]); 5 4 3 2 1
Array before Array after
printf(“\nReverse order printing a[0]=1 a[0]=1
a[1]=2 a[1]=2
of array\n”); a[2]=3 a[2]=3
a[3]=4 a[3]=4
for(i=n-1;i>=0;i--) // reverse loop a[4]=5 a[4]=5
printf(“%d\n”,a[i]);
2/22/2020 CSE 1001 Department of CSE 14
Write a program to reverse an array using only
one array
Example : a[ ]={1, 2, 3, 4, 5}
int a[20], i, j, n, temp;
Enter values
printf("enter n \n“); n=5
12345
scanf(“%d”,&n); Reversed array
5 4 3 2 1
printf("\n Enter values for an array“); Array Reversed
array
for(i=0;i<n;i++) a[0]=1 a[0]=5
a[1]=2 a[1]=4
scanf(“%d”,&a[i]); a[2]=3 a[2]=3
a[3]=4 a[3]=2
Contd… a[4]=5 a[4]=1
/ / f indin g p o s it ion
for(i=0;i<n;i++) New array after inserting 3 :
a[ ] = {1, 2, 3, 4, 5,6}
if (ele<a[i]) break;
pos = i+1; //position of insertion
for(i=n; i>=pos; i--) //shift the elements to right
a[i]=a[i-1];
a[pos-1] = ele;//ele is inserted at the specified pos.
n = n + 1; // increment the count of no of elements
2/22/2020 CSE 1001 Department of CSE 19
Summary
• Arrays
• Problems on 1D arrays
Memory Requirement:
Total size =size *(sizeof(data_type));
Initialization:
type array-name [size]={list of values}