Single Dimensional Array in C: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-08 11:50:13   27651  Share
Subject Syllabus DetailsSubject Details 8 Questions 30 Program
☰ TContent
☰Fullscreen

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

Types of Array in c programming language

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] ; Types of Array in c programming language

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<stdio.h>
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<stdio.h>
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<stdio.h>
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<stdio.h>
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

  1. Two Sum
  2. Contains Duplicate
  3. Best Time to Buy and Sell Stock
  4. Merge Sorted Array
  5. Majority Element
  6. Remove Duplicates from a Sorted Array
  7. Max Consecutive Ones
  8. Check if array is sorted and rotated
  9. Move Zeroes
  10. Single Number
  11. Pascal's Triangle
  12. Rotate Array
  13. .........
  14. Majority Element II
  15. Product of Array Except for Self
  16. Maximum Subarray/ Maximum Sum Subarray/ Kadane's Algorithm
  17. Maximum Product Subarray
  18. Container With Most Water
  19. Missing Number
  20. Longest Consecutive Sequence
  21. Set Matrix Zeroes
  22. Spiral Matrix
  23. Rotate Image
  24. Rearrange array elements by sign
  25. Next Permutation
  26. .........
  27. Subarray sum equals k
  28. Merge Intervals
  29. Find the Duplicate Number
  30. Repeat and Missing Number Array
  31. Count Inversions
  32. Search in a 2D Matrix
  33. Pow(x, n)
  34. Unique Paths
  35. 3Sum
  36. 4Sum
  37. Largest Subarray with Sum 0
  38. Subarray with given XOR

Strings

  1. Valid Palindrome
  2. Valid Anagram
  3. Roman To Integer
  4. Longest Common Prefix
  5. Find the index of the first occurrence in a string
  6. Remove Outermost Parentheses
  7. Isomorphic Strings
  8. Largest Odd Number in String
  9. Rotate String
  10. Maximum Nesting Depth of the Parenthes
  11. Sum of beauty of all substrings
  12. Minimum add to make parentheses-valid
  13. Group Anagrams
  14. Longest Palindromic Substring
  15. Palindromic Substrings
  16. Encode and Decode Strings
  17. Reverse words in a string
  18. Minimum Characters required to make a string palindrome
  19. String to Integer Atoi
  20. Count and Say
  21. Compare Version Numbers
  22. Sort Characters by Frequency
  23. Shortest Palindrome
  24. Longest Happy Prefix

Heaps

  1. Kth Largest Element in a Stream
  2. Kth Largest Element in an array
  3. Top K Frequent Elements
  4. Task Scheduler
  5. Hand of Straights
  6. Design Twitter
  7. Maximum Sum Combinations
  8. Merge K Sorted Lists
  9. Find Median from Data Stream

Linked List

  1. Reverse a Linked List
  2. Detect Cycle in a Linked List
  3. Middle of the Linked List
  4. Merge Two Sorted Lists
  5. Intersection of two linked lists
  6. Palindrome Linked List
  7. Delete the middle node of a linked list
  8. Odd Even Linked List
  9. Delete Node in a Linked List
  10. Linked List Cycle II
  11. Add Two Numbers
  12. Remove Nth Node From End Of List
  13. Reorder List
  14. Flattening a Linked List
  15. Copy List with Random Pointer
  16. Sort List
  17. Rotate List
  18. Reverse Nodes in K Group
  19. Merge K Sorted Lists

Stack & Queues

  1. Valid Parentheses
  2. Implement Stack using Queues
  3. Next Greater Element I
  4. Nearest Smaller Element
  5. Sum of Subarray Minimums
  6. Online Stock Span
  7. Sum of subarray ranges
  8. Remove K Digits
  9. LRU Cache
  10. Largest Rectangle in Histogram
  11. Maximal Rectangle

Binary Search

  1. Binary Search
  2. Search Insert Position
  3. Kth Missing Positive Number
  4. Find first and last position of element in sorted array
  5. Search in a rotated sorted array
  6. Search in a rotated sorted array II
  7. Find Minimum in Rotated Sorted Array
  8. Single Element in a Sorted Array
  9. Allocate Books
  10. Aggressive Cows
  11. Kth Element of Two Sorted Array
  12. Longest Increasing Subsequence
  13. Median of Two Sorted Arrays
  14. Find Peak Element
  15. Koko Eating Bananas
  16. Minimum Number of days to make m bouquets
  17. Find the smallest divisor given a threshold
  18. Capacity to ship packages within D Days
  19. Find a peak element II
  20. Search in a 2D matrix
  21. Search in a 2D matrix II
  22. Split Array Largest Sum

Greedy

  1. N Meetings in One Room
  2. Lemonade Change
  3. Assign Cookies
  4. JUMP Game
  5. Valid Parenthesis String
  6. Insert Interval
  7. Merge Intervals
  8. Non-overlapping intervals
  9. Minimum Platforms
  10. Job Sequencing Problem

Trees

  1. Invert/Flip Binary Tree / Mirror Tree
  2. Inorder Traversal
  3. Preorder Traversal
  4. Postorder Traversal
  5. Count Complete Tree Nodes
  6. Subtree of Another Tree
  7. Same Tree
  8. Symmetric Tree
  9. Maximum Depth of Binary Tree
  10. Diameter of Binary Tree
  11. Balanced Binary Tree
  12. Search in a Binary Search Tree
  13. Insert into a Binary Search Tree
  14. Two Sum IV Input is a BST
  15. Floor From BST
  16. Ceil From BST
  17. Left View of Binary Tree
  18. Bottom View of Binary Tree
  19. Top View of a Binary Tree
  20. Right Side View
  21. Level Order Traversal
  22. Lowest Common Ancestor of a Binary Tree
  23. Binary Tree Zigzag Level Order Traversal
  24. Convert Sorted Array to Binary Search Tree
  25. Delete Node in a BST
  26. Maximum Width of Binary Tree
  27. Binary Tree Maximum Path Sum
  28. Construct Binary Tree from Preorder and Inorder Traversal
  29. Binary Tree Level Order Traversal
  30. Validate Binary Search Tree
  31. Flatten Binary Tree to Linked List
  32. Populating next right pointers in each node
  33. Kth Largest Element in a BST
  34. Kth Smallest Element in a BST
  35. All Nodes Distance K in Binary Tree
  36. Predecessor and Successor
  37. Lowest Common Ancestor of a Binary Search Tree
  38. Recover Binary Search Tree
  39. Vertical Order Traversal of a Binary Tree
  40. Serialize and Deserialize Binary Tree

Dynamic Programming

  1. Delete Operation for Two Strings
  2. Number of longest increasing subsequence
  3. Count Square Submatrices with all ones
  4. Longest Common Subsequence
  5. Best time to buy and sell stock with cooldown
  6. Partition array for maximum sum
  7. Palindromic Partitioning
  8. Matrix Chain Multiplication
  9. Minimum Cost to Cut a Stick
  10. Partition Array into two arrays to minimize sum difference
  11. Minimum Insertion Steps to make a string palindrome
  12. Shortest Common Supersequence
  13. Matrix Chain Multiplication
  14. Minimum Cost to Cut a Stick
  15. Partition Array into two arrays to minimize sum differen
  16. Minimum Insertion Steps to make a string palindrome
  17. Shortest Common Supersequence
  18. Distinct Subsequence
  19. Wildcard Matching
  20. Burst Balloons
  21. Parsing a boolean expression
  22. Maximal Rectangle

MCQ Available

There are 23 MCQs available for this topic.

23 MCQTake Quiz