CodesandTutorials
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.
You are here - Home > Programming > C > Basics

Simple Array Program


Description

Array is a collection of similar data-type elements, which are stored in consecutive memory location under common variable name.

Syntax

data-type arrayname[size of array];

Eg. int a[10];

  • Array many be one-dimensional or multi-dimensional.
  • Array data-type and size must be declared, before it is being used.
  • Array index starts with zero and ends with less than one the size of the array.
  • Size of the array should be integer.

Initialisation

Eg.
    int a[4] = {12,46,32,53};
    float values[] = {33.23,53.31,53.68};

In the first example we have declared and initialized 4 elements of the array, while in the second we have directly initialized the array elements with float data-type as defining the size of array is optional.

Source code

  • //Simple program using Array
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • int A[5],i;
  • int B[5] = {32,43,3,58,423};
  • clrscr();
  • printf("Enter the elements to store in array:");
  • for(i=0;i<4;i++)
  • {
  • scanf("%d",&A[i]);
  • }
  • printf("\nEntered elements of A array are:\n");
  • for(i=0;i<4;i++)
  • {
  • printf("%d\n",A[i]);
  • }
  • printf("\nStored elements of B array are:\n");
  • for(i=0;i<4;i++)
  • {
  • printf("%d\n",B[i]);
  • }
  • getch();
  • }

Program working steps

  • First line is the comment, 2nd and 3rd lines are preprocessor directives and 4th line is the main function from where the program execution starts.
  • On 5th line we have declared an array int A[5] means array can store 5 elements of integer data-type.
  • On 6th line an integer data-type array of size 5 with elements is initialized within the curly brackets and separated by commas.
  • Then using for loop, user is prompted to enter array elements for array A. These elements are sequentially stored starting from A[0], A[1]... till A[4].
  • Now using same for loop the array elements from array A is printed, and similarly array elements from array B is printed.
  • getch() to wait for the user command to exit.

Tip Box

Array elements have garbage value, until you specify values to the elements.


Advertisement





Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved