Arrays in C allows storing of similar data types in contiguous memory locations. The document provides code examples to initialize and traverse arrays, take user input to store in an array, calculate the average of numbers in an array, sort an array, and find the largest and second largest elements in an array. Functions like for loops, if statements and printfs are used to manipulate array elements.
2. An array is defined as the collection of similar type of data
items stored at contiguous memory locations.
3. //Array Initialization and Traversal
#include<stdio.h>
int main()
{
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d n",marks[i]);
}//end of for loop
return 0;
}
4. // Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%dn", values[i]);
}
return 0;
}
5. // Program to find the average of n numbers using arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum variable
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
6. Sorting an array
#include<stdio.h>
void main ()
{ int i, j, temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
} } }
printf("Printing Sorted Element List ...n");
for(i = 0; i<10; i++)
{ printf("%dn",a[i]);
}
7. Program to print the largest and second
largest element of the array.
#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}
8. #include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}