C programming tutorial

                  PREVIOUS                                                                                  
.

 

C array

 

Sometimes in C programming there is need of 100s of variables.Its not a good option to first declare 100 variable ,giving them different names and then assigning them value by using 100s of scanf.Here comes the concept of array in C .C provide a better option to do this by using arrays

 

Suppose we want 50 int variables,insted of declaring 50 integer variables individually we will declare one array capable of holding 50 integer values.

 

int a[50];

'a' is the name given to array.It will hold 50 integer values.Its not compulsory to give array name 'a'.We can give array any name according to our wish,example int num[50].

 

So the next question comes how we will store values in this array.First value will be stored in a[0],2nd in a[1],3rd in a[2] and so on.

 

Following is the way to assign values to array.

a[0]=2;

a[1]=5;

a[2]=5;

.

.

.

a[49]=6;

 

a[0] will refer to first varfiable,a[1] will refer to second variable and a[49] will refer to fiftieth variable.

 

If we want to print value in varable a[2] we will use printf in following way.

printf("%d",a[2]);

 

If want to take input from user and store it in a[2].

scanf('%d",&a[2]);

 

It would be cumbersome if we will use 50 scanf statements to store 50 values in this array.So there is another method to do this.We will use a loop to do this

for(int i=0;i<50;i++)

{

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

}

This loop will store 1st value in a[0],2nd in a[1],and so on till a[49].Hence by writing 3 lines of code we were able to store 50 values using array in C.It would be very difficult if we would have used 50 different varibles and writing 50 scang to input values.

 

Similarly we can print values stored in array using printf inside loop.

for(int i=0;i<50;i++)

printf("%d",a[i]);

Memory representation of arrays

1 integer takes 2 bytes.

When we decla0re array of 50 then 50x2=100 continous bytes will be allocated to array in memory.

Suppose memory was allocated from memory address 1001 to1100.1001 and 1002 will be named as a[0],1003 and 1004 will be named as a[1] and so on.So value of a[0] will be stored in locations 1001 and 1002.

 

if there is a character array

char b[50];

1 character takes 1 byte in memory.So 50x1=50 continous bytes will be allocated to this array.b[0] will be stored in first of these bytes,b[1] will be stored in second of these bytes and so on.

 

array example

let us make a program using array in C that calculate average profit of 30 days.

#include<stdio.h>

main()

{ float profit[30],total=0;

printf("%d",Enter the profits);

for(int i=0;i<30;i++)

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

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

tottal=total+profit[i];

printf("avg is %d",total/30.0;

}

I hope this c tutorial would have made your concept of array clear.

 


                  PREVIOUS