Code Scrappers

ARRAYS, STRINGS AND FUNCTIONS

Arrays

In C programming, one of the common problem is to handle similar types of data. For example: If the user want to store names of 200 employees. This can be done by creating 200 variable individually but, this process is very slow and impracticable. These sorts of problems can be handled in C programming using arrays.

An array is a sequence of data item of same type.
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays

Declaration of arrays

One-dimensional arrays

Initialization of one-dimensional array:
Arrays can be initialized at the time of declaration in the source code as:
int price[5]={5,25,55,75,100};
It is not absolutely necessary to define the size of arrays during initialization.
int price[ ]={5,25,55,75,100};

Declaration of one-dimensional arrays

data_type array_name[array_size];

For example:
int number[10];
Here, the name of array is number. The size of array is 10,i.e., there are 10 elements of array number.
Every element in an array is of the same data type.

Array elements

Size of array defines the total number of elements in an array.Each element of an array can be accessed by the user based on the need of program.

For example :
int age[5];

NOTE 1: In an array,the positioning begins with 0 instead of 1

Here, the size of array age is 5 times the size of int since there are 5 elements in the array age.
Suppose, the starting address of age[0] is 2120d and the it is known that the size of int is 4 bytes. Then, the next address a[1] will be 2124d, that of a[2] will be 2128d and so on.

Example of array in C programming

#include<stdio.h>

void main()

{

int marks[10];
int i,number,sum=0;

printf("Please enter the total number of students: \n");

scanf("%d",&number);

for(i=0;i<number;++i)

{

	printf("Please enter the marks of student%d: ",i+1);

	scanf("%d",&marks[i]);

	sum=sum+marks[i];

}

printf("Total sum=%d\n", sum);

}


Output:
Please enter the total number of students: 3
please enter the marks of student1: 12
Please enter the marks of student2: 31
Please enter the marks of student3: 2
sum=45

Output:
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45

<< Back Next >>