EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Arrays in C Programming

Home » Software Development » Software Development Tutorials » C Programming Tutorial » Arrays in C Programming

Arrays in C Programming

Introduction to Arrays in C Programming

The array is a type of data structure that is used to store homogeneous data in contiguous memory locations. Following is an arrays in C programming.

Arrays in C Programming

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Here index refers to the location of an element in the array. Let us imagine if A[L] is the name of the array where “A” is the variable name and “L” is the length of the array, i.e the number of elements present in the array.

Then A[i] represents the element at that “i+1”th position in the array .for example:

A[6]= 72 means element at 6+1 th location of array.

Need for Array

It helps to represent a large number of elements using a single variable. It also makes accessing of element faster easy to store in memory location using the index of the array that represents the location of an element in the array..

Accessing Elements in Array

Accessing any element in the array is much easier and can be done in O(1) complexity

Popular Course in this category
C Programming Training (3 Courses, 5 Project)3 Online Courses | 5 Hands-on Projects | 34+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,570 ratings)
Course Price

View Course

Related Courses
C++ Training (4 Courses, 5 Projects, 4 Quizzes)Java Training (40 Courses, 29 Projects, 4 Quizzes)

Indexes of an array start from 0 till -1.0 indicates the first element of the array and -1 indicates the last element of the array. Similarly, -2 indicates the last but one element of the array.

For Example:

Let A be an array with length 7 and one needs to access the element with value 94 then he must use A[3].

Accessing Elements in Array

 

Accessing Elements in Array

Syntax

printf(”%d”, A[3]) – This will print 94 where 3 is the index which we need to access and a is the variable of the array.

 Declaration of Array in C

In C, the array must be declared properly before using it with its name and length. There is three syntaxes in which we can declare arrays in a c program

 Syntax 1

int A[7] = {21,56,32,52,63,12,48} – Declaring the length and elements of array

 C Program

#include<stdio.h>
int main{
int a[7] = {21,56,32,52,63,12,48};
int i;
for(i=0;i<7;i++){
printf(“%d\n”,a[i]);
}
return 0;
}

Output:

Arrays in C Programming-1

Syntax 2

int  A[]={21,56,32,52,63,12,48} – Declaring the length of elements of array

C Program

#include<stdio.h>
int main{
int a[] = {21,56,32,52,63,12,48};
int i;
for(i=0;i<7;i++){
printf(“%d\n”,a[i]);
}
return 0;
}

Output:

Arrays in C Programming-2

Syntax 3

int  A[7]; – Declaring the length of array only.

C Program

#include<stdio.h>
int main{
int a[7] ;
int i;
printf(“Please enter the array elements”);
for(i=0;i<7;i++){
scanf(“%d\n”,&a[i]);
}
printf(“Elements of array are”);
for(i=0;i<7;i++){
printf(“%d\n”,a[i]);
}
return  0;
}

Output:

 Arrays in C Programming-3                 

Syntax 4

int A[7] ={0};- Declaring length of the array and the element when an element is the same at all positions.

C Program

#include<stdio.h>
int main{
int a[7]={0} ;
int i;
printf(“Elements of array are”);
for(i=0;i<7;i++){
printf(“%d\n”,a[i]);
}
return  0;
}

Output:

Arrays in C Programming-4

Syntax 5

Declaring length of array and also the value of elements where all values are same

Case1 – int a[3] = {[0..1]=3} –

Case 2 – int a[3] ={0};-

Syntax 6

 int *a;- Declaring array as a pointer to the location of elements.

No Index Out of Bound Checking

In case one attempts to access the element out of bounds of the array, no error is shown by compiler instead it generates a warning. And also gives an unexpected output.

Example

a[4] ={2,3,4,5};

If we write printf(a[4]);

The output will be 225263545 – Unexpected

Also, In C, it is compiler does not error to initialize an array with more number elements than the specified length in the declaration. For example, the below program does not show an error instead.

C Program

#include<stdio.h>
int main{
int arr[2]={10,22,56,32,45,89} ;
int i;
printf(“Elements of array are”);
for(i=0;i<2;i++){
printf(“%d\n”,arr[i]);
}
return  0;
}

Output:

No Index Out of Bound Output

Retrieval of Elements in Array

Retrieval of elements of an array and printing them is a very easy task. It just requires one loop to print n elements of an array. thus the complexity of such a program is O(n).

For eg- let int a[7] ={23,56,8,944,58,24,5};

Program for printing the elements of an array is

C Program

#include<stdio.h>
int main{
int arr[7]={23,56,8,944,58,24,5} ;
int i;
printf(“Elements of array are”);
for(i=0;i<7;i++){
printf(“%d\n”,arr[i]);
}
return  0;
}

Output:

Retrieval of Elements Output

Multidimensional Array

C language also allows multidimensional arrays,i.e` arrays that can hold elements in rows as well as columns.

Declaration

While declaring the multidimensional array one must specify the length of all dimensions except the left one because that is optional.

Example

Declaring array in the below manner will result in an error as dimensions other than left most is not specified.

Int a[][][2]={

{{1, 2}, {3, 4}},

{{5, 6}, {7, 8}}

}

Example

Below is one of the correct syntax for declaration of multidimensional array in C.

Int a[][3]={

{52,56,86},{44,6,21}

}

Passing Array as Parameter in Function

Sometimes while making a function, we require the function to use a number of variables that it needs to take from different functions. That time those variables must be passed as a parameter to for that function call. But eventually, as the number of variables increase, we must use an array to pass the variable or in case some operations need to be performed on the arrays then also need arises to pass a complete array as a parameter in a function. For passing an array as a variable to the function :

1. Call by Value

In this type of method calling, the actual values of the array are copied to the formal parameter where both are stored in different location thus any change made in the values does not get reflected in the function.

C Program

#include <stdio.h>
Void show( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
show(arr[x]);//value of array //elements are passed as an argument
}
return 0;
}

Output:

Call by Value Output

2. Call by Reference

While calling a function when instead of passing the actual values of the array, the reference to the variable is passed as a parameter then it is known as call by reference.

C Program

#include <stdio.h>
Void show( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {1,2,3,4,5,6,7,8,9,0};
for (int x=0; x<10; x++)
{
show(&arr[x]);//reference of array //elements are passed as an argument
}
return 0;
}

Output:

Call by Reference Output

3. Passing the Whole Array as an Argument

Eg – Let arr be an array of 7 elements.disp is a function to display the elements of an array which take 2 arguments, first that points to the first location of the array and other the length of the array(var2).while calling the function arr variable that points to the location of the first element of array and length i.e 7 is passed. 

C Program

#include <stdio.h>
void disp( int *var1, int var2)
{
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {12, 22, 38,85, 65, 66, 77};
disp(var_arr, 7);
return 0;
}

Output:

Passing Whole Array Output

Memory Allocation of Array

Memory representation in C language is considered to be divided into 5 sections as given below:-

  1. Text segment
  2. Initialized data segment
  3. Uninitialized data segment
  4. Stack
  5. Heap

Data, heap, and stack are the three segments where arrays can be allocated memory to store its elements, the same as other variables.

  1. Dynamic Arrays: Dynamic arrays are arrays, which needs memory location to be allocated at runtime. For these type of arrays memory is allocated at the heap memory location.
  2. Global or Static Arrays: These are the type of arrays that are allocated at compile time. Thus data segment memory is always allocated for these type of arrays.
  3. Local Arrays: The arrays which get initialized inside a function or block are known as local arrays. These types od arrays get memory allocated on the stack segment.

Character Array

 In C, strings are considered as a single-dimensional array of characters with null character  ‘\0’ in its last position that compiler automatically adds to it.

For example “i love coding” is considered as a single dimension array in c of length 14 including ‘\0’ character in the end.

Declaration: There are 2 ways to declare and initialize the character array-

  1. char str[12] = “i love code”;
  2. char str[12] = {‘I’,’ ‘,’l’,’o’,’v’,’e’,’ ‘,’c’,’o’,’d’,’e,’\0’’}; – Here we must end it with ‘\0’ character at the end.
  3. Char ch[3] = ‘modi’ – Illegal declaration

Taking Input and Output

While taking input and displaying output in C for char array ‘%c’ can be used scanf() and printf()  function respectively.

While implementing the same for strings “%s” can be used, but stops scanning on the occurrence of first whitespace character.

C Program:

#include <stdio.h>
#include<string.h>
int main()
{
char str[20];
printf(“Enter a string”);
scanf(“%[^\n]”,&str);
printf(“%s”,str);
return 0;
}

Output:

Taking Input and Output

 Other than printf and scanf functions, C also provides string functions such as gets() and puts() to ignore white spaces of string while scanning and printing.

Conclusion

Array is a type of data structure used to store the homogeneous data in a contiguous memory location. Arrays in Programming are used as a representation for different complex data structures such as a tree, heap, etc.C language allows multidimensional arrays for all primitive data types. Strings are also represented as a character array with the null character ‘\0’ as its last character. Arrays in Programming allow the fast retrieval and direct accessing of elements of array using the index where the element is stored.

Recommended Articles

This is a guide to Arrays in C Programming. Here we discuss the Introduction, Needs of Array, along with Passing Array Functions includes Call by Value, Call by Reference, and Passing whole array as an argument. You may also look at the following articles to learn more –

  1. 3D Arrays in C
  2. Patterns in C Programming
  3. 3D Arrays in C++
  4. Arrays in PHP

C Programming Training (3 Courses, 5 Project)

3 Online Courses

5 Hands-on Projects

34+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C Programming Tutorial
  • Array
    • Arrays in C Programming
    • 2-D Arrays in C
    • 3D Arrays in C
    • Multidimensional Array in C
    • Array Functions in C
    • Strings Array in C
  • Basic
    • Introduction to C
    • What is C
    • Career in C Programming
    • Advantages of C
    • How to Install C
    • Best C Compilers
    • Data Types in C
    • Variables in C
    • C Keywords
    • C Command
    • Command Line Arguments in C
    • C Literals
    • Constants in C
    • Unsigned Int in C
    • String in C
  • Pointers
    • Pointers in C
    • Null pointer in C
    • Function Pointer in C
    • Double Pointer in C
    • Void Pointer in C
    • Const Pointer in C
    • Dangling Pointers in C
    • Pointer Arithmetic in C
  • Operators
    • C Operators
    • Arithmetic Operators in C
    • Relational Operators in C
    • Assignment Operators in C
    • Logical Operators in C
    • Conditional Operator in C
    • Modulus Operator in C
    • Ternary Operator in C
    • Address Operator in C
    • Unary Operator in C
    • Operators Precedence in C
    • Left Shift Operator in C
  • Control Statement
    • Control Statements in C
    • If Statement in C
    • If-else Statement in C
    • Else if Statement in C
    • Nested if Statement in C
    • #else in C
    • Structure Padding in C
    • Nested Structure in C
    • Continue Statement in C
    • Break Statement in C
    • Switch Statement in C
    • Goto Statement in C
  • Loops
    • Loops in C
    • For Loop in C
    • While Loop in C
    • Do While Loop in C
    • Nested Loop in C
    • Infinite Loop in C 
  • Function
    • Math Functions in C
    • Hashing Function in C
    • Recursive Function in C
    • Power Function in C
    • fputs in C
    • C puts() Function
    • fprintf() in C
    • fseek() in C
    • Stderr in C
    • ASCII Value in C
    • strcat() in C
    • Inline Function in C
    • sizeof() in C
    • Function Prototype in C
    • C ftell()
  • Sorting
    • Sorting in C
    • Heap Sort in C
  • Advanced
    • Constructor in C
    • Encapsulation in C
    • C Storage Classes
    • Static Keyword in C
    • File Handling in C
    • Queue in C
    • Hexadecimal in C 
    • typedef in C
    • Memory Allocation in C
    • Linked List in C
    • Volatile in C
    • Tokens in C
    • Expression in C
    • Regular Expression in C
    • Error Handling in C
    • Types of Errors in C
    • Preprocessor in C
    • Preprocessor Directives in C
    • fscanf() in C
    • #Pragma in C
    • #ifndef in C
    • #undef in C
    • Macros in C
  • C programs
    • Patterns in C Programming
    • Star Patterns in C
    • Number Patterns in C
    • Swapping in C
    • Reverse Number in C
    • Palindrome in C Program
    • Factorial in C
    • Fibonacci Series in C
    • Square Root in C
    • Random Number Generator in C
    • Prime Numbers in C
    • Escape Sequence in C
    • Reverse String in C
    • Leap Year Program in C
    • Anagram Program in C
    • Strong Number in C
    • String Concatenation in C
    • C Programming Matrix Multiplication
    • Decimal to Octal in C
    • Expression Evaluation in C
    • Decimal to Hexadecimal in C
  • Interview question
    • C Programming Interview Questions

Related Courses

C Programming Training Course

C++ Training Course

Java Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C Programming Training (3 Courses, 5 Project) Learn More