One Dimensional Array In C
A one-dimensional array in C is a linear collection of elements of the same type, accessed by an index. It's declared using square brackets [] to specify the size of the array.
Here's the syntax for declaring a one-dimensional array in C:
datatype arrayName[arraySize];
For example, if you want to declare an array of integers with 5 elements:
int numbers[5];
This declaration allocates memory for 5 integers in a contiguous block, accessible through the numbers variable.
Entering data into a one dimensional array in C
Store marks obtained by 5 students in a class.
float marks[5];
int i;
printf("\nEnter marks obtained by 5 students: \n");
for(int i=0;i<5;i++)
{
scanf("%f",&marks[i]);
}
Reading data from one dimensional array in C
Find the total marks of a class of 5 students
for(int i=0;i<5;i++)
{
sum = sum + marks[i];
}
Write a C program to calculate average marks of class with 5 students.
#include<stdio.h>
int main()
{
float marks[5],sum=0;
int i;
printf("\nEnter marks obtained by 5 students: \n");
for(int i=0;i<5;i++)
{
scanf("%f",&marks[i]);
}
for(int i=0;i<5;i++)
{
sum = sum + marks[i];
}
printf("\nThe average marks of class: %.2f\n", (sum / 5));
return 0;
}
Output:
Enter marks obtained by 5 students:
75
78
80
89
90
The average marks of class: 82.40
Write a C program to find the largest number in a given array.
#include <stdio.h>
int main() {
int arr[20],size=5;
// Input elements of the array
printf("Enter %d elements of the array:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Find the largest number
int largest = arr[0]; // Assume the first element is the largest
for (int i = 1; i < size; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
// Output the result
printf("The largest number in the array is: %d\n", largest);
return 0;
}
Output:
Enter 5 elements of the array:
10
100
20
50
40
The largest number in the array is: 100
Write a C program to sort the given array in ascending order. [Bubble sort In C ]
#include <stdio.h>
int main() {
int arr[20],size=5,temp;
// Input elements of the array
printf("Enter %d elements of the array:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Bubble Sort algorithm to sort the array
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Output the sorted array
printf("Sorted array in ascending order:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Enter 5 elements of the array:
10
-1
0
4
3
Sorted array in ascending order:
-1 0 3 4 10