Arrays
Arrays
For Eg.
int number[30];
float marks[60];
char name[15];
Single Integer
a=5; 2005 5
integer Array
1 2 3 4 7 12 13 15 89 ……….
a= ‘5’; 5
2006
Character Array
N I T R K L \0
char college_name[7]={‘N’,’I’,’T’,’R’,’k’,’l’,’\0’};
342901 ? 0 X Identifier
342905 ? 1
342909 23 2
342913 ? 3
Value
Another array example
x[0]=23; /* valid */
x[2.3]=5; /* invalid: index is not an int */
return 0;
}
Examples
int x [5] = { 1,2,3,4,5 }; size 10 bytes
creates array with elements 0-4 values 1-5
• x[i]
• y[i][j]
• z[i][j][k]
Some more tips..
double a[n];
× Size can not be a Variable
Declaration: Declaration:
datatype name_of_array[20]; datatype name_of_array[20][20];
Initialization: Initialization:
name_of_array[20]={1,2,3,4……16}; name_of_array[20][20]={{1,2,3,4},
{2,3,4,5},{5,6,7,8}};
Examples
• Assuming we have the following array b:
0 1
0 1 0
1 3 4
if( a[i][j]%2== 0 )
{
printf( “ even= %d”, a[i][j] );
else
printf( “ odd= %d”,a[i][j] );
}
}
What is string?
Array of characters.
char month1[]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};
char month1[]=“january”;
Example
#include<stdio.h>
main()
{
char strc[]=“this is a string literal”;
printf(“%s”,strc); only name of the array
} format specifier for string
this is a string literal
Array of strings
#include<stdio.h>
const int Num=5;
const int length=9;
main()
{
int j;
char Names[Num][length]={“Tejaswi”,”Prasad”,
”Prashant”,”Anand”, “Priya”};
for(j=0;j<Num;j++) printf(“%s\n”,Names[j]);
Output:
Tejaswi
Prasad
Prasanth
Anand
Input/output
gets(string) performs input operation .
Read This:
strncpy()
strncat()
strstr()
#include<stdio.h>
main()
{
char ar[20]=“Arvind”;
printf(“%d”,strlen(ar));
}
#include<stdio.h>
#include<string.h>
void main()
{ int i;
char name[20]=“home";
char name1[20]="sweet";
i=strcmp(name,name1); // name<name1
printf("%d”,i);
}
-11
Example
#include<stdio.h>
#include<string.h>
void main()
{ char name1[20];
char name2[20]=“harry”;
strcpy(name1,name2);
printf(“%s”,name1);
}
harry
Example
#include<stdio.h>
#include<string.h>
main( )
{int i;
char name1[20]="home";
char name2[20]="sweet";
strcat(name2,name1);
printf("%s",name1); }
sweethome
Assignments - IV
WAP to insert one integer element at a given position in
the array of integers