Single Dimensional Array in C: Usage and Examples
Table of Content:
The C language provides a capability that enables the user to design a set of similar data types, called array. This tutorial describes how arrays can be created and manipulated in C.
Why array is important ?
As you might already now, data types can store only one value at a time. Therefore, you would not be able to have a data type that contains more than one slot to store more than one variable. This is where arrays come in. Arrays are simply data types that can store more than one variable. Each variable is stored in an array element.
What are Arrays ?
An array is a collection of variables of the same type that are referred to through a common name. A specific element in an array is accessed by an index. In C, all arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Arrays can have from one to several dimensions. The most common array is the string, which is simply an array of characters terminated by a null.
Types of Arrays in C
Single-Dimension Arrays
Now we will discuss about Single-Dimension Arrays in c programming language.
Array Declaration
Like other variables, arrays must be explicitly declared so that the compiler can allocate space for them in memory.
The general form for declaring a single-dimension array is
datatype var_name[size];
Here, type declares the base type of the array, which is the type of each element in the array
size defines how many elements the array will hold.
int rollNo[10];
int marks[10] ;
Array Initialization
We managed to store values in them during program execution. Let us now see how to initialize an array while declaring it. Following are a few examples that demonstrate this.
int roll[6] = { 2, 4, 12, 5, 45, 5 } ; int array[ ] = { 2, 4, 12, 5, 45, 5 } ; float points[ ] = { 12.3, 34.2 -23.4, -11.3 } ;Note the following points carefully:
(a) Till the array elements are not given any specific values, they are supposed to contain garbage values.
(b) If the array is initialized where it is declared, mentioning the dimension of the array is optional as in the 2nd example above
Accessing Elements of an Array
Once an array is declared, let us see how individual elements in the array can be referred. This is done with a subscript, the number in the brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, roll[2]
is not the second element of the array, but the third.
marks[0]
= 1st Array Element marks[1]
= 2nd Array Element marks[2]
= 3rd Array Element marks[3]
= 4th Array Element marks[4]
= 5th Array Element marks[5]
= 6th Array Element marks[6]
= 7th Array Element marks[7]
= 8th Array Element marks[8]
= 9th Array Element marks[9]
= 10th Array Element Entering/Inserting Data into an Array
You can places data into an array by specifing the index positions:
marks[0] = 12 ; marks[1] = 13 ; marks[2] = 14 ; marks[3] = 15 ; marks[4] = 16 ; marks[5] = 17 ; marks[6] = 18 ; marks[7] = 19 ; marks[8] = 10 ; marks[9] = 11 ;
Here is the section of code that places data into an array:
for ( i = 0 ; i <= 10 ; i++ ) { printf ( " Enter marks: " ) ; scanf ( "%d", &marks[i] ) ; }
Reading/Accessing Data from an Array
Access specific element using their index value
printf("%d", marks[0] ) ; printf("%d", marks[1] ) ; printf("%d", marks[2] ) ; printf("%d", marks[3] ) ; printf("%d", marks[4] ) ; printf("%d", marks[5] ) ; printf("%d", marks[6] ) ; printf("%d", marks[7] ) ; printf("%d", marks[8] ) ; printf("%d", marks[9] ) ;
Access All element using for loop or any other loop
for ( i = 0 ; i <= 10 ; i++ ) { printf("%d", marks[i] ) ; }
Example Program
Program 1
#include void main( ) { int marks[10] ; /* array declaration */ marks[0] = 11; /* store data in array */ marks[1] = 12; marks[2] = 13; marks[3] = 14; marks[4] = 15; marks[5] = 16; marks[6] = 17; marks[7] = 18; marks[8] = 10; marks[9] = 11; printf("\nEnter marks %d",marks[0]) ; /* read data from an array*/ printf("\nEnter marks %d",marks[1]) ; printf("\nEnter marks %d",marks[2]) ; printf("\nEnter marks %d",marks[3]) ; printf("\nEnter marks %d",marks[4]) ; printf("\nEnter marks %d",marks[5]) ; printf("\nEnter marks %d",marks[6]) ; printf("\nEnter marks %d",marks[7]) ; printf("\nEnter marks %d",marks[8]) ; printf("\nEnter marks %d",marks[9]) ; }
Output
Enter marks 11 Enter marks 12 Enter marks 13 Enter marks 14 Enter marks 15 Enter marks 16 Enter marks 17 Enter marks 18 Enter marks 10 Enter marks 11
Program 2
#include void main( ) { int i ; int marks[10] ; /* array declaration */ for(i = 0 ; i < 10 ; i++){ printf ( "\nEnter marks:") ; scanf ( "%d", &marks[i] ) ; /* store data in array */ } for(i = 0 ; i < 10 ; i++){ printf("\nEnter marks %d",marks[i]) ; /* read data from an array*/ } }
Output
Enter marks:12 Enter marks:13 Enter marks:14 Enter marks:15 Enter marks:16 Enter marks:17 Enter marks:18 Enter marks:19 Enter marks:10 Enter marks:11 Enter marks 12 Enter marks 13 Enter marks 14 Enter marks 15 Enter marks 16 Enter marks 17 Enter marks 18 Enter marks 19 Enter marks 10 Enter marks 11
What is integer array in C programming?
An integer array consists of only integer numbers, for instance, if you have
the array of size 5 with interger type data int_array[5]
it means that your
first element int_array[0]
is an integer number like 1, or 15 and so on. The
same is true for other elements too;
int_array[1] (int_array[2], int_array[3],int_array[4])
might be any integer element and so on.
Another Example
#include int main(void) { int n[100]; /* this declares a 100-integer array */ int t; /* load x with values 0 through 99 */ for(t=0; t<100; ++t) { n[t] = t; } /* display contents of x */ for(t=0; t<100; ++t) { printf("%d \t", n[t]); } return 0; }
Output
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 Press any key to continue . . .
Another Example on Average
#include void main() { int average, add = 0 ; int i ; int marks[10] ; /* array declaration */ for ( i = 0 ; i < 10 ; i++) { printf("\nEnter marks ") ; scanf("%d",&marks[i]) ; /* store data in array */ } for ( i = 0 ; i < 10 ; i++ ){ add = add + marks[i] ; /* read data from an array*/ average = add / 10 ; } printf ( "\nAverage marks = %d \n", average ) ; }
Output
Enter marks 1 Enter marks 2 Enter marks 3 Enter marks 4 Enter marks 5 Enter marks 6 Enter marks 7 Enter marks 8 Enter marks 9 Enter marks 10 Average marks = 5 Press any key to continue . . .
What is the application of arrays in C programming?
Array is used in C to store data of similar data type. Arrays are used when we
want to store data in large quantities, e.g. if we want to store 100 numbers we
have to declare 100 variables and remembering the name of each variable is a very
a difficult task, here comes the array we can declare a single variable int
num[100]
now this variable can store 100 different or same numbers and can be
accessed by referencing as num[0], num[1], num[2]
and so on. So, we can say that
to reduce efforts we use arrays.
What is Array in c programming?
An array in C programming is a homogeneous user-defined datatype consisting of multiple data elements occupying contiguous memory locations. Homogeneous means that the array can only consist of elements of a single data type. Contiguous means that the elements of the array occupy (logically) adjacent memory locations.
What is the importance of array in C programming?
Arrays allow similar types of data to be stored within a contiguous block of memory such that every data element is accessible in constant time, regardless of its physical location within the array. This is achieved through simple pointer arithmetic treating each element as a memory offset from the start of the array. Since every element is the same length (in bytes), locating any element is simply a matter of calculating its offset from its index. Indices are zero-based thus the third element can be found at index 2. The memory offset for that element is therefore the product of the element size and 2. However, C permits indices to be specified directly, while the pointer arithmetic is done in the background. Thus array_name[2] automatically returns a reference to the third element. Arrays with large and complex variable length data elements need to store those elements separately from the array, usually non-contiguously. This is achieved by using a pointer array. Pointer arrays are particularly useful when sorting extremely large data lists as it is much easier and more efficient to implement a sorting algorithm with an array than it is with a linked list, particularly when constant-time random-access is essential to the algorithm. The time and effort in building the array is generally more than compensated for by the efficiency of the algorithm. Arrays can also be divided and subdivided to better model the data they represent. For instance, a chessboard might be implemented as a one-dimensional array of 64 elements, however it makes more sense to model the chessboard in a two-dimensional array of 8x8 elements. Although the array is still allocated contiguously and can be thought of as being 8 rows and 8 columns, it's actually better to think of this two-dimensional array as being a one-dimensional array of 8 elements, where each element is another one-dimensional array of 8 elements. By thinking this way it makes it possible to allocate extremely large arrays in non-contiguous memory (as completely separate one-dimensional arrays) and also makes comprehension of a four-dimensional array in a three-dimensional world that much easier (unless you actually want to model time and space of course).A four-dimensional array can be thought of in a variety of ways: as being a one dimensional array of three-dimensional arrays, or as a two-dimensional array of two-dimensional arrays, or as a three-dimensional array of one-dimensional arrays, or even as a one-dimensional array of one-dimensional arrays of one-dimensional arrays of one-dimensional arrays. Whichever method you use to imagine your array is immaterial, so long as it makes sense to you that's all that really matters.
Some Standard Problems on Array
Arrays
- Two Sum
- Contains Duplicate
- Best Time to Buy and Sell Stock
- Merge Sorted Array
- Majority Element
- Remove Duplicates from a Sorted Array
- Max Consecutive Ones
- Check if array is sorted and rotated
- Move Zeroes
- Single Number
- Pascal's Triangle
- Rotate Array
- .........
- Majority Element II
- Product of Array Except for Self
- Maximum Subarray/ Maximum Sum Subarray/ Kadane's Algorithm
- Maximum Product Subarray
- Container With Most Water
- Missing Number
- Longest Consecutive Sequence
- Set Matrix Zeroes
- Spiral Matrix
- Rotate Image
- Rearrange array elements by sign
- Next Permutation
- .........
- Subarray sum equals k
- Merge Intervals
- Find the Duplicate Number
- Repeat and Missing Number Array
- Count Inversions
- Search in a 2D Matrix
- Pow(x, n)
- Unique Paths
- 3Sum
- 4Sum
- Largest Subarray with Sum 0
- Subarray with given XOR
Strings
- Valid Palindrome
- Valid Anagram
- Roman To Integer
- Longest Common Prefix
- Find the index of the first occurrence in a string
- Remove Outermost Parentheses
- Isomorphic Strings
- Largest Odd Number in String
- Rotate String
- Maximum Nesting Depth of the Parenthes
- Sum of beauty of all substrings
- Minimum add to make parentheses-valid
- Group Anagrams
- Longest Palindromic Substring
- Palindromic Substrings
- Encode and Decode Strings
- Reverse words in a string
- Minimum Characters required to make a string palindrome
- String to Integer Atoi
- Count and Say
- Compare Version Numbers
- Sort Characters by Frequency
- Shortest Palindrome
- Longest Happy Prefix
Heaps
- Kth Largest Element in a Stream
- Kth Largest Element in an array
- Top K Frequent Elements
- Task Scheduler
- Hand of Straights
- Design Twitter
- Maximum Sum Combinations
- Merge K Sorted Lists
- Find Median from Data Stream
Linked List
- Reverse a Linked List
- Detect Cycle in a Linked List
- Middle of the Linked List
- Merge Two Sorted Lists
- Intersection of two linked lists
- Palindrome Linked List
- Delete the middle node of a linked list
- Odd Even Linked List
- Delete Node in a Linked List
- Linked List Cycle II
- Add Two Numbers
- Remove Nth Node From End Of List
- Reorder List
- Flattening a Linked List
- Copy List with Random Pointer
- Sort List
- Rotate List
- Reverse Nodes in K Group
- Merge K Sorted Lists
Stack & Queues
- Valid Parentheses
- Implement Stack using Queues
- Next Greater Element I
- Nearest Smaller Element
- Sum of Subarray Minimums
- Online Stock Span
- Sum of subarray ranges
- Remove K Digits
- LRU Cache
- Largest Rectangle in Histogram
- Maximal Rectangle
Binary Search
- Binary Search
- Search Insert Position
- Kth Missing Positive Number
- Find first and last position of element in sorted array
- Search in a rotated sorted array
- Search in a rotated sorted array II
- Find Minimum in Rotated Sorted Array
- Single Element in a Sorted Array
- Allocate Books
- Aggressive Cows
- Kth Element of Two Sorted Array
- Longest Increasing Subsequence
- Median of Two Sorted Arrays
- Find Peak Element
- Koko Eating Bananas
- Minimum Number of days to make m bouquets
- Find the smallest divisor given a threshold
- Capacity to ship packages within D Days
- Find a peak element II
- Search in a 2D matrix
- Search in a 2D matrix II
- Split Array Largest Sum
Greedy
- N Meetings in One Room
- Lemonade Change
- Assign Cookies
- JUMP Game
- Valid Parenthesis String
- Insert Interval
- Merge Intervals
- Non-overlapping intervals
- Minimum Platforms
- Job Sequencing Problem
Trees
- Invert/Flip Binary Tree / Mirror Tree
- Inorder Traversal
- Preorder Traversal
- Postorder Traversal
- Count Complete Tree Nodes
- Subtree of Another Tree
- Same Tree
- Symmetric Tree
- Maximum Depth of Binary Tree
- Diameter of Binary Tree
- Balanced Binary Tree
- Search in a Binary Search Tree
- Insert into a Binary Search Tree
- Two Sum IV Input is a BST
- Floor From BST
- Ceil From BST
- Left View of Binary Tree
- Bottom View of Binary Tree
- Top View of a Binary Tree
- Right Side View
- Level Order Traversal
- Lowest Common Ancestor of a Binary Tree
- Binary Tree Zigzag Level Order Traversal
- Convert Sorted Array to Binary Search Tree
- Delete Node in a BST
- Maximum Width of Binary Tree
- Binary Tree Maximum Path Sum
- Construct Binary Tree from Preorder and Inorder Traversal
- Binary Tree Level Order Traversal
- Validate Binary Search Tree
- Flatten Binary Tree to Linked List
- Populating next right pointers in each node
- Kth Largest Element in a BST
- Kth Smallest Element in a BST
- All Nodes Distance K in Binary Tree
- Predecessor and Successor
- Lowest Common Ancestor of a Binary Search Tree
- Recover Binary Search Tree
- Vertical Order Traversal of a Binary Tree
- Serialize and Deserialize Binary Tree
Dynamic Programming
- Delete Operation for Two Strings
- Number of longest increasing subsequence
- Count Square Submatrices with all ones
- Longest Common Subsequence
- Best time to buy and sell stock with cooldown
- Partition array for maximum sum
- Palindromic Partitioning
- Matrix Chain Multiplication
- Minimum Cost to Cut a Stick
- Partition Array into two arrays to minimize sum difference
- Minimum Insertion Steps to make a string palindrome
- Shortest Common Supersequence
- Matrix Chain Multiplication
- Minimum Cost to Cut a Stick
- Partition Array into two arrays to minimize sum differen
- Minimum Insertion Steps to make a string palindrome
- Shortest Common Supersequence
- Distinct Subsequence
- Wildcard Matching
- Burst Balloons
- Parsing a boolean expression
- Maximal Rectangle