Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Arrays
An array is collection of similar data items that are stored under a common name.
Each array element is referred by specifying the array name followed by one or more
subscript ([ ]).
Syntax
datatype array_name[size of array];
Example
int arr[10]; // can collect 10 integer values with a common
name specified “arr”
int data type
arr identifier/name of array
[10] size of array also called as subscript.
Some more examples of an array are,
float value[5]; // can collect 5 float values with a common
name specified “value”
char name[20]; // can collect 20 characters under same name.
Memory allocation
Memory allocation of an array is based on the type of data collected together.
Illustration of how memory is allocated for an array is given below.
1. int a[5];
Index 0 1 2 3 4
a 10 20 30 40 50
1
Types of array
There are three types of array can be used in C Language. They are,
One-dimensional array
Two-dimensional array
Multi-dimensional array
One-dimensional Two-dimensional Multi-dimensional
Contain only one Contain two subscript Contain more than one
subscript subscript
Syntax Syntax Syntax
datatype name[size] datatype datatype
name[size1][size2] name[size1][size2][size3]
Example Example Example
int mark[5]; int matrix[3][3]; int cube[5][5][5]
0 1 2
0 1 2 3 4 0 1 2 3
10 20 30 40 50 1 4 5 6
2 7 8 9
mark[2] = 30
Matrix[1][2] = 6
Index 0 1 2 3 4 5 6 7 8 9
value 10 20 30 40 50 60 70 80 90 95
Array size is usually omitted when single constant is assigned. Here proper array size is
assigned automatically. This includes NULL character ‘\0’ at the end of the string. Normally
‘\0’ indicates the end of the string.
Index 0 1 2 3 4
color R O S E \0
2
color[2] = ‘S’
color[3] = ‘E’
color[4] = ‘\0’
Initialization of one dimensional array
After declaration, the array elements must be initialized otherwise they hold garbage
value. Initialization of an array can be performed during,
a. Compile time b) Run time
a. Compile time
Initialization of an array at the time of declaration is known as Compile time
initialization.
Example:
int a[5] = {10, 20, 30, 40, 50};
Values/elements of an array is enclosed in brace { } and separated by comma (,).
b. Run time
Initialization of an array during run time is known as Compile time initialization.
When users have many elements in array, it can be initialized at run time.
Example1:
int a[5];
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
Example2:
float b[20];
for(i=0;i<20;i++)
{
scanf(“%f”,&b[i]);
}
Here in above example, values of an array are initialized or assigned during run time by
getting the input values from the user.
Example programs for one-dimensional array
1. Write a C program to find average on ‘n’ marks
#include<stdio.h>
#include<conio.h>
void main()
{
int mark[10],n,i,sum=0; //One dimensional array declaration
float avg;
clrscr();
printf("\nEnter number of marks:");
scanf("%d",&n);
printf("Enter %d marks one by one:",n);
for(i=1;i<=n;i++)
{
scanf("%d",&mark[i]); //get input values
sum=sum+mark[i]; //calculate sum
}
printf("\nSum=%d",sum);
avg=sum/n; //calculate average
printf("\nAverage=%f",avg);
getch();
}
3
Output
Enter number of mark: 5
Enter 5 marks one by one:
90
80
90
80
70
Sum=410
Average=82.00
Output
Enter the string: madam
Given string is Palindrome
Enter the string: welcome
Given string is not Palindrome
a[1][0] = 40
a[1][1] = 50
a[1][2] = 60
a[2][0] = 70
a[2][1] = 80
a[2][2] = 90
5
Initialization of two dimensional array
After declaration, the array elements must be initialized otherwise they hold garbage
value. Initialization of an array can be performed during,
a. Compile time
b. Run time
a. Compile time
Initialization of an array at the time of declaration is known as Compile time
initialization.
Example:
int matrix[3][3] = {0,0,0,1,1,1,2,2,2};
Or
int matrix[3][3] = { {0,0,0} , {1,1,1} , {2,2,2} };
Values/elements of an array is enclosed in brace { } and separated by comma (,).
b. Run time
Initialization of an array during run time is known as Compile time initialization.
When users have many elements in array, it can be initialized at run time.
Example:
int matrix[3][3];
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf(“%d”,&matrix[i][j]);
}
}
Here in above example, values of an array are initialized or assigned during run time by
getting the input values from the user.
9
4. Write a C program to find product of 2 matrices
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],row,col,i,j,k;
clrscr();
printf("Enter the no.of rows:");
scanf("%d",&row);
printf("Etner the no.of columns:");
scanf("%d",&col);
printf("Enter the matrix A element:");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the matrix B element:");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
c[i][j]=0;
for(k=0;k<row;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Multiplication of matrix is:\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
10
OUTPUT:
Enter the no.of rows:2
Etner the no.of columns:2
Enter the matrix A element:
1 2
3 4
Enter the matrix B element:
1 2
3 4
Multiplication of matrix is:
7 10
15 22
Multi-dimensional array
An array with more than one subscript is called as multi-dimensional array. It
represents table, matrix, cube, diamond etc.
Syntax
datatype array_name[size1][size2].... [sizen];
Example1:
int a[3][3];
int cube[2][4][6];
Disadvantage of an array
1. Elements in array must be of same data type.
2. Using an array user cannot collect data with different data type.
3. Size of an array is fixed. It is not possible to extend an array size during run time.
4. Insertion and deletion requires more time, because the elements are shifted entirely.
Important Questions
Two mark
1. Define an array.
2. List out the characteristics of an array.
3. What are the types of array? How it varies?
4. How to initialize an array during compile time and run time?
5. What is multi dimensional array?
6. State the disadvantages of an array.
16 mark
11
STRINGS
String
A String is a sequence of characters enclosed within double quotes. A string is a
sequence of characters that is treated as a single data item. The compiler automatically adds
a NULL character (\0) at the end of the string constant to indicate the end of the string.
Example1:
“Computer Programming” , “Duraisamy”
Example2:
char name[6] = “TAMIL”;
0 1 2 3 4 5
name T A M I L \0
Number of bytes required to store a string constant is one more than number of
characters. NULL character (\0) occupies one byte. But length of the string will not include
the NULL character. In the above example number of bytes allocated is 5, but length of the
string “TAMIL” is 4.
Declaration of string
C Language does not support string data type. String used as array of characters.
Syntax
char string_name[size];
Example
char text[10];
Initialization of String
char name[10]=”computer”;
char name[ ] = {‘C’,’ o’, ’m’, ’p’, ’u’, ’t’, ’e’, ’r’}
Index 0 1 2 3 4 5 6 7 8 9
value 10 20 30 40 50 60 70 80 90 95
Example
1. Write a C program to get and print a string on the output screen
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf("\nEnter String:");
scanf("%s",str); //get/read the input string
printf("\nEntered String is:%s",str); //write the given string
getch();
}
12
Output
Enter String: Computer
Entered String is: Computer
13
Standard String operations
C Language contains large number of string functions. These string functions uses
standard header file “string.h”. There are five important string handling functions in C
language.
String function Purpose
strcat (s1,s2) Concatenates two string
strcmp(s1,s2) Compares two string
strcpy(s1,s2) Copies one string over the another string
strlen(s1) Find the length of a string
strrev(s1) Reverse the given string
i. strcat(s1,s2)
This string function is used to concatenate two given strings. Joining two strings is
called as concatenation.
Syntax
strcat(str1,str2);
Here, String str2 is joined with String str1
Example:
str1 = Computer
str2 = Science
strcat(str1,str2);
Result after the string operation
str1 = ComputerScience
str2 = Science
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
clrscr();
printf("\nEnter the string1:");
gets(s1);
printf("\nEnter the string2:");
gets(s2);
strcat(s1,s2);
printf("\nConcatenated String:%s",s1);
getch();
}
Output
Enter string1: Computer
Enter string2: Science
Concatenated String: ComputerScience
ii. strcmp(s1,s2)
This string function is used to compare two given strings. If two strings are identical
then this functions returns 0. If two string are identical, it returns numerical value i.e.,
difference between ASCII values of strings.
14
str1 == str2 Returns 0
str1 > str2 Returns positive (+ve) value
str1 < str2 Returns negative (-ve) value
Syntax
strcmp(str1,str2);
or
value=strcmp(str1,str2)
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
int value;
clrscr();
printf("\nEnter the string1:");
gets(s1);
printf("\nEnter the string2:");
gets(s2);
value=strcmp(s1,s2);
if(value==0)
{
printf("\nFunction returns:%d",value);
printf("\nStrings are Identical");
}
else
{
printf("\nFunction returns:%d",value);
printf("\nStrings are nor Identical");
}
getch();
}
Various Output
Enter string1: Computer
Enter string1: Computer
Enter string2: computer
Enter string2: Computer
Function Returns: -32
Function Returns: 0
Strings are not Identical
Strings are Identical
Enter string1: Abi Enter string1: Bala
Enter string2: Bala Enter string2: Abi
Function Returns: -1 Function Returns: 1
Strings are not Identical Strings are not Identical
Enter string1: Abi Enter string1: Chitra
Enter string2: Chitra Enter string2: Abi
Function Returns: -2 Function Returns: 2
Strings are not Identical Strings are not Identical
Enter string1: Abi Enter string1: Anu
Enter string2: Anu Enter string2: Abi
Function Returns: -12 Function Returns: 12
Strings are not Identical Strings are not Identical
15
iii. strcpy(s1,s2)
This string function is used to copy the source string to the destination string.
Syntax
strcpy(destination,source);
Here, source string will be copied to the destination string. Old content of destination
string is replaced with new content
Example:
str1 = Computer
str2 = Science
strcpy(str1,str2);
Result after the string operation
str1 = Science
str2 = Science
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
clrscr();
printf("\nEnter the string1:");
gets(s1);
printf("\nEnter the string2:");
gets(s2);
strcpy(s1,s2);
printf("\nAfter string copying\nSting1=%s\nString2=%s",s1,s2);
getch();
}
Output
Enter string1: Computer
Enter string2: Science
After string copying
String1=Science
String2=Science
iv. strlen(s1)
This string function is used to find the length of the string. This function returns the
length of the string. White space is counted for determining the length of the string. The
terminating NULL character ‘\0’ is not counted while determining the length of the string.
Syntax
len=strlen(string);
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20];
int len;
clrscr();
printf("\nEnter the string:");
16
gets(s1);
len=strlen(s1);
printf("\nLength of the given string is %d",len);
getch();
}
Output
Enter string: Computer
Length of the given string is 8
Enter string: Computer Science
Length of the given string is 16
Enter string: ComputerScience
Length of the given string is 15
v. strrev(s1)
This string function is used to reverse all the characters of the given string except the
NULL character.
Syntax
strrev(string);
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20];
clrscr();
printf("\nEnter the string:");
gets(s1);
strrev(s1);
printf("\nReverse of the given string is %s",s1);
getch();
}
Output
Enter string: Computer
Reverse of the given string is retupmoC
Enter string: madam
Reverse of the given string is madam
Sample code for String Handling functions
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
int len;
clrscr();
printf("\nEnter the string1:");
gets(s1);
printf("\nEnter the string2:");
scanf("%s",s2);
strcat(s1,s2);
printf("\n\nString Concatenation:%s",s1);
strcpy(s1,s2);
17
printf("\n\nAfter String Copy\n\nString1=%s\n\nString2=%s",s1,s2);
if(strcmp(s1,s2)==0)
printf("\n\nString are identical");
else
printf("\n\nString are not identical");
len=strlen(s1);
printf("\n\nLength of String \" %s \" is %d",s1,len);
strrev(s1);
printf("\n\nReverse of the string is %s",s1);
getch();
}
Output
Enter string1: Computer
Enter string2: science
String Concatenation: Computerscience
After String Copy
String1=science
String2=science
Strings are identical
Length of string “science” is 7
Reverse of string is ecneics
18
Character test functions
The C language support many character testing functions also. These functions are
used to test the character typed from the keyboard is a letter or a digit or a special character
and prints message accordingly.
String
Test Purpose Example Result
functions
Let, ch=6
TRUE
isdigit(ch);
isdigit(ch) To test ‘ch’ is a digit/number
Let, ch=’a’
FALSE
isdigit(ch);
Let, ch=6
FALSE
isalpha(ch);
isalpha(ch) To test ‘ch’ is an alphabet
Let, ch=’a’
TRUE
isalpha(ch);
Let, ch=6
TRUE
To test ‘ch’ is an alphanumeric isalnum(ch);
isalnum(ch)
character Let, ch=’a’
TRUE
isalnum(ch);
Let, ch=’ ’
isspace(ch) To test ‘ch’ is a blank space? TRUE
isspace(ch);
Let, ch=’A’
FALSE
islower(ch);
islower(ch) To test ‘ch’ is lowercase or not
Let, ch=’a’
TRUE
islower(ch);
Let, ch=’A’
TRUE
isupper(ch);
isupper(ch) To test ‘ch’ is uppercase or not
Let, ch=’a’
FALSE
isupper(ch);
Convert given character to Let, ch=’A’
tolower(ch) ch=’a’
lowercase tolower(ch);
19
SIMPLE PROGRAMS
SORTING
1. SORT N-NAME ALPHABETICALLY
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[30][10],temp[30];
int n,i,j;
clrscr();
printf("\nEnter the no.of entries:");
scanf("%d",&n);
printf("Enter the names one by one:");
for(i=0;i<n;i++)
{
scanf("%s",name[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("The names alphabetical order:\n");
for(i=0;i<n;i++)
printf("\n%s\t",name[i]);
getch();
}
OUTPUT
20
2(A). SORT N NUMBERS – ASCENDING ORDER
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,t;
clrscr();
printf("Enter num of elements:");
scanf("%d",&n);
printf("Enter the numbers to be sorted:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("Sorted elements are:\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}
OUTPUT
21
2(B). SORT N NUMBERS – DESCENDING ORDER
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,t;
clrscr();
printf("Enter num of elements:");
scanf("%d",&n);
printf("Enter the numbers to be sorted:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("Sorted elements are:\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}
OUTPUT
22
3. FIND GREATEST OF N-NUMBERS IN ARRAY
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,t;
clrscr();
printf("Enter num of elements:");
scanf("%d",&n);
printf("Enter the numbers to be sorted:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("Greatest number in array is:%d",a[0]);
getch();
}
OUTPUT
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,t;
clrscr();
printf("Enter num of elements:");
scanf("%d",&n);
printf("Enter the numbers to be sorted:");
for(i=0;i<n;i++)
23
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("Smallest number in array is:%d",a[0]);
getch();
}
OUTPUT
Important Questions
Two mark
1. Define a String.
2. How to declare a string?
3. List out various standard string functions used in C.
4. State the purpose of strlen( ) function with example.
5. List character test function? Give example.
16 mark
24