1-D Array

One Dimensional Array in C

  • We can declare an array in the c language in the following way.
data_type array_name[array_size];  

  • Now, let us see the example to declare array.
int marks[5];  
  • Here, int is the data_type, marks is the array_name and 5 is the array_size.

https://mskuthar.blogspot.com/2015/02/1-d-array.html
1-D Array

Initialization of C Array

  • A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].
marks[0]=2;//initialization of array  
marks[1]=8;  
marks[2]=7;  
marks[3]=6;  
marks[4]=0;  
https://mskuthar.blogspot.com/2015/02/1-d-array.html
Array Declaration

C array example


#include <stdio.h>    
#include <conio.h>    
void main(){    
int i=0;  
int marks[5];//declaration of array  
clrscr();    
marks[0]=80;//initialization of array  
marks[1]=60;  
marks[2]=70;  
marks[3]=85;  
marks[4]=75;  
//traversal of array  
for(i=0;i<5;i++){    
printf("%d \n",marks[i]);  
}//end of for loop  
getch();    
}

Output
80
60
70
85
75

C Array: Declaration with Initialization


  • We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};  

  • In such case, there is no requirement to define size. So it can also be written as the following code.

int marks[]={20,30,40,50,60};  

  • Let's see the full program to declare and initialize the array in C.

#include <stdio.h>    
#include <conio.h>    
void main(){    
int i=0;  
int marks[5]={20,30,40,50,60};//declaration and initialization of array  
clrscr();    
//traversal of array  
for(i=0;i<5;i++){    
printf("%d \n",marks[i]);  
}  
getch();    
}    
Output
20
30
40
50
60

// Program to take 5 values from the user and store them in an array and printing the elements stored in the array.
#include <stdio.h>
#include<conio.h>
void main() 
{
  int values[5];
  printf("Enter 5 numbers ");
  // taking input and storing it in an array
  for(int i = 0; i < 5; ++i) {
     scanf("%d", &values[i]);
  }
  printf("Displaying numbers: ");
  // printing elements of an array
  for(int i = 0; i < 5; ++i) {
     printf("%d\n", values[i]);
  }
  getch();
}
Expected Output:
Enter 5 numbers
7
9
8
4
6
Displaying numbers:
7
9
8
4
6

Post a Comment

Previous Post Next Post