One Dimensional Array

One Dimensional Array:

Syntax : data-type array_name[array_size];

Array declaration, initialization and accessing in c Examples
Array declaration syntax:

data_type array_name [array_size];

Array initialization syntax:

data_type array_name [array_size]=(value1, value2, value3,….);

Array accessing syntax: array_name[index];

Integer array example:

int age1 [5];

int age1[5]={0, 1, 2, 3, 4};

age1[0]; /*0 is accessed*/

age1[1]; /*1 is accessed*/

age1[2]; /*2 is accessed*/

Character array example:

char str1[10];

char str1[10]={‘H’,‘a’,‘i’};

(or)

char str1[0] = ‘H’;

char str1[1] = ‘a’;

char str1[2] = ‘i;

str1[0]; /*H is accessed*/

str1[1]; /*a is accessed*/ str1[2]; /*i is accessed*/

Example 1

#include<stdio.h>

int main()

{

int p;

int arr1[5] = {10,20,30,40,50}; // declaring and Initializing array in C

//To initialize all array elements to 0, use int arr1[5]={0};

/* Above array can be initialized as below also

arr1[0] = 10;

arr1[1] = 20;

arr3[2] = 30;

arr4[3] = 40;

arr5[4] = 50; */

for (p=0;p<5;p++)

{

// Accessing each variable

printf(“value of arr1[%d] is %d \n”, p, arr1[p]);

}

return 0;

}

Output

value of arr1[0] is 10

value of arr1[1] is 20

value of arr1[2] is 30

value of arr1[3] is 40

value of arr1[4] is 50

WAP to find the average of n (n < 10) numbers using arrays

#include<stdio.h>

int main()

{

int marks1[10], i1, n1, sum1 = 0, average1;

printf(“Enter n1: “);

scanf(“%d”, &n1);

for(i1=0; i1<n1; ++i1)

{

printf(“Enter number%d: “,i1+1);

scanf(“%d”, &marks1[i1]);

sum1 += marks1[i1];

}

average1 = sum1/n1;

printf(“Average marks = %d”, average1);

return 0;

}

Output

Enter n: 2

Enter number1: 45

Enter number2: 67

Average = 56

Leave a Reply

Your email address will not be published. Required fields are marked *