0% found this document useful (0 votes)
91 views46 pages

Arrays Strings-Program-Notes

This document discusses arrays, strings, and pointers in C programming. It covers defining and declaring one-dimensional and multi-dimensional arrays, initializing array values, and accessing array elements. It also discusses defining strings, reading and writing strings, and processing strings. Finally, it provides an overview of pointers, including pointer declaration and usage.

Uploaded by

kalpana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views46 pages

Arrays Strings-Program-Notes

This document discusses arrays, strings, and pointers in C programming. It covers defining and declaring one-dimensional and multi-dimensional arrays, initializing array values, and accessing array elements. It also discusses defining strings, reading and writing strings, and processing strings. Finally, it provides an overview of pointers, including pointer declaration and usage.

Uploaded by

kalpana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

4 .

1 | Arrays, Strings and Pointers

UNIT IV

 Arrays: Defining an array- Processing an array


 Multi-dimensional arrays
 Strings: Defining a string-Null character-initialization of strings
 reading and writing a string- ARRAYS
 processing the string
 Pointers: fundamentals – Pointer Declaration & Usage

ARRAYS
An array is a collection of similar data items that are stored under a common name.

4.1 DEFINING AN ARRAY


 A value in array is identified by index or subscript enclosed in square
brackets with array name.
The individual data items can be characters, integers, floating-point numbers, etc.
However, they must all be of the same type and the same storage class. Fig 4.1 shows
the memory allocation of array named X and storage of 7 elements into it.
X

x[0] x[1] x[2] …………………..x[n-1]

Fig .4.1: Array storage


 Each array element (i.e., each individual data item) is referred to by specifying the array
name followed by one or more subscripts, with each subscript enclosed in square
brackets
 In general terms, a one-dimensional array definition/declaration can be expressed as
4 .2 | Arrays, Strings and Pointers

data- type arrayname[ size] ;


 data- type is the type elements stored in array
 arrayname is the name of the array and expression is a positive-valued
integer expression which indicates the number of array elements.

4.2 DECLARING AN ARRAY:


To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows:
<data type> < arrayName> [ Size ];
The array Size must be an integer constant greater than zero and type can be any
valid C data type.
Examples:
int x[l00];
char text [ 8 0 ] ;
static char message[25];
static float n[12];
 The first line states that x is a 100-element integer array, and the second defines text
to be an 80-element character array.
 In the third line, message is defined as a static 25-element character array.
 The fourth line establishes n as a static 12-element floating- point array

4.3 ARRAY INITIALIZATION:


The values can be initialized to an array, when they are declared like ordinary
variables, otherwise they hold garbage values.
The array can be initialized in the following two ways:
1. At compile time
2. At runtime
4.3.1. At compile time:
Syntax:
data- type arra_name [ size] = { value 1, value 2, . . . , value n) ;
Eg: int marks[3]= { 70,80,90 }
Like ordinary variables , the values to the array can be initialized as follows:
marks[0]= 70
marks[1]= 80
marks[2]= 90
Character array can be used in the program like ordinary variables.Character can
also be initialized in the similar fashion.
char name[ ]={‘L’,’A’,’K’}
4 .3 | Arrays, Strings and Pointers

The above ststement declares the name as an array of character initialisez with the string
‘LAK’

Examples
int a[3] = {2, 3, 5};
char ch[20] = "TechnoExam" ;
float stax[3] = {5003.23, 1940.32, 123.20} ;

4.3.2. At run time:


The array can also be initialized by reading data item from the input.
Eg: int n[2];
Scanf(“%d %d”,&n[0],n[1]);
If more number of elements then reading statement as follows:
for(i=0;i<size;i++)
scanf(“%d”. &n[i]);

4.4 ACCESSING ARRAY ELEMENTS

An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array.

For example:
int salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary
variable.

Following is an example which will use all the above mentioned three concepts viz.
declaration, assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
4 .4 | Arrays, Strings and Pointers

/* output each array element's value */


for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}

Output:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

4.5 TYPES OF AN ARRAY:


1. One / Single Dimensional Array
2. Two Dimensional Array
3. Multidimensional Array

4.5.1 One Dimensional Array

For a one-dimensional array, the size is specified by a positive integer


expression, enclosed in square brackets. The expression is usually written as a
positive integer constant.
The general form is
data- type array [ expression] = { value 1, value 2, . . . , value n) ;
 where value 1 refers to the value of the first array element, value 2 refers to the value of
the second element, and so on. The appearance of the expression, which indicates the
number of array elements, is optional when initial values are present.
Total Size (in Bytes):
4 .5 | Arrays, Strings and Pointers

total size = length of array * size of data type


In above example, a is an array of type integer which has storage size of 3 elements. The
total size would be 3 * 2 = 6 bytes.

Memory Allocation of a single dimensional array is shown in Fig.4.2

Fig 4.2: Memory allocation for one dimensional array

Processing an Array
Single operations which involve entire arrays are not permitted in C. Thus, if a and b
are similar arrays (i.e., same data type, same dimensionality and same size), assignment
operations, comparison operations, etc. must be carried out on an element-by-element
basis.

Sample Program to read 3 elements in an array and print the same


#include <stdio.h>
#include <conio.h>
void main()
{
int a[3], i;;
clrscr();
printf("\n\t Enter three numbers : ");
for(i=0; i<3; i++)
{
scanf("%d", &a[i]); // read array
}
printf("\n\n\t Numbers are : ");
for(i=0; i<3; i++)
{
printf("\t %d", a[i]); // print array
}
4 .6 | Arrays, Strings and Pointers

getch();
}
Output :
Enter three numbers: 9 4 6
Numbers are: 9 4 6

Sample Program to read age of 5 members and display in reverse order


#include <stdio.h>
int main()
{
int age[5];
printf(“Enter the age of 5 members”);
for(i=0;i<5;i++)
scanf("%d",&age[i]);
for(i=4;i>=0;i--)
printf("\n%d",age[i]);
}
Output:
Enter the age of 5 members 67 34 56 18 45
45
18
56
34
67

4.5.2 Two Dimensional Array


The array which is used to represent and store data in a tabular form is called as
'two dimensional array.' Such type of array specially used to represent data in a matrix
form.
The following syntax is used to represent two dimensional array.
Syntax:
<data-type> <array_name> [row_subscript][column-subscript];
Example:
int a[3][3];
float x[4][3];
In above example, a is an array of type integer which has storage size of 3
* 3 matrix. The total size would be 3 * 3 * 2 = 18 bytes.
4 .7 | Arrays, Strings and Pointers

Memory allocation of a two dimensional array is shown in Fig 4.3

Fig.4.3:Memory allocation for two dimensional array

Reading two dimensional array of size m x n


for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
scanf(“%d”, &a[i][j]);
Sample Program to find the sum of diagonal elements using 2-dimensional array
#include<stdio.h>
void main()
{
int matrix[3][3],i,j,sum;
sum=0;
printf(“Enter the elements”);
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf(“%d”,&matrix[i][j]);
}
}
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
if(i==j)
sum=sum+matrix[i][j];
}
}
printf(“sum=%d”,sum);
}
4 .8 | Arrays, Strings and Pointers

OUTPUT
Enter the elements
1 2 3
2 2 3
3 3 3
sum=6
Limitations of two dimensional array:
 We cannot delete any element in 2D array.
 If we don’t know that how many elements have to be stored in a memory in
advance, then there will be memory wastage if large array size is specified.

4.5.3 Multidimensional Arrays

 In some cases there is a need for arrays with a third or even a fourth dimension.
These arrays are called multidimensional arrays.
 These multidimensional arrays relatively infrequently.
 They can facilitate an understanding of the data, improve the readability of
algorithms, and facilitate processing since the data can be processed through the use
of three or more nested loops.
 For example, with input data on temperatures referenced by day, city, county, and
state, day would be the first dimension, city would be the second dimension, county
would be the third dimension, and state would be the fourth dimension of the array.
 In any case, any temperature could be found as long as the day, the city, the county,
and the state are known.
 A multidimensional array allows the programmer to use one array for all the data.

 Fig.4.4 shows a block of memory locations and their reference names for a three-
dimensional array. The recommended variable names for the indexes of a three
dimensional array are Row for row, Column for column, and Depth for depth.
 For a fourth dimension, Volume for volume is used. These arrays are processed
much like two-dimensional arrays.
4 .9 | Arrays, Strings and Pointers

Fig.4.4: Three Dimensional Array

4.6 STRINGS
Definition
A string is an array of characters terminated by a special symbol named as null
character (represented as ‘\0’). Hence null character is also named as string-
termination character. It is used to identify the length of the string and expresses the
end of string.
4.6.1Defining a string
A string definition expressed as
char string-name [size];.
 Size is a positive-valued integer expression which indicates the number of elements in
the string including null character.
Ex:
char name [50];
/* name is a string that can consist of maximum 50 characters */

4.6.2 Null Character


 Null character is used to terminate the string. It is needed to compute the actual length
of the string. As compared to other arrays, the string size is not stored in a separate
variable and string reading, writing etc.
Ex:
char name [50] =”welcome”;
4 .10 | Arrays, Strings and Pointers

 The length of actual string is 7. In the case 8th element of the array i.e. name [7] location
will be used to store null character, as shown in Fig 4.5 & 4.6.

W E L C O M E ‘\0’
[0] [1] [2] [3] [4] [5] [6] [7] [49]
Fig 4.5: String storage
 Null character is used to identify the string termination and no processing is done after
the identification of null character.
 Thus reading, writing, copying a string will be processed up to the null character’s
position i.e. up to subscript number 7 in above example.
 The null character is not counted towards the length of the string, but takes memory of
one element. Null character cannot be read or written, but is used internally only.

4.6.3 Initialization of Strings

 The strings can be initialized at the time of definition. It can also be initialized using
double quotes.
EX:
char str[30] = ”Hello World”;
char str[[30] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’};
H E l l o W o r l D \0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [29]

Fig 4.6: String storage

 In both cases, the null character will get appended at the last automatically. Both of
these initializations will result into storage as shown in figure.
4.6.4 Reading and Writing a String
 A string can be read and written by using a single scanf and printf function using %s (s
stands for string) and no loop is needed, which was compulsory for reading & writing
arrays of other data types.
Example :
/** Read a string from keyboard and display the same on screen **/
#include<stdio.h>
#define MAX_SIZE 50
main()
{
char str [Max_SIZE];
4 .11 | Arrays, Strings and Pointers

printf(“Enter a string of maximum %d characters:”, MAX_SIZE);


scanf(”%s”, str);
printf(“The entered string is %s\n”, str);
}
Output:
Enter a string of maximum 49 characters: programming
The entered string is programming
Enter a string of maximum 49 characters: C Program
The entered string is C

 This scanf function reads a string from keyboard till a whitespace character (blank, tab,
newline) is encountered.
 After the reading is complete, the null character is appended automatically at the next
position inside the array.
 In first case, the input word programming gets stored at str[0] to str[10] and null
character is appended at str[11].
 The scanf function with %s can be used to read strings not consisting of spaces. So if we
gave C Program as input, only c gets read. So the null character is appended at str[1] in
case the input was “c program”.
 If we are interested to read a string consisting of blank characters as well e.g. we want
to read a line of text, gets function is the easiest way to do it.
 But the string.h header file must be included to use gets function.
 Th e gets function keeps on reading the characters till the newline character (Enter key)
is not pressed.
 Similarly for printing a string puts function can be used. The gets and puts functions can
be used as follows:
gets (string-name);
puts (string);
where the string-name refers to the variable name of string. The puts function can
be used to print a constant string written within double quotes as well as string
variable.
 The gets function also appends null character at the end of the string automatically, as
done in case of scanf with %s.
Example:
#include<stdio.h>
#include<string.h>
#define MAX_SIZE 50
main()
4 .12 | Arrays, Strings and Pointers

{
char str [MAX_Size];
printf(“Enter a line of text of maximum %d characters:”, MAX_SIZE);
gets(str);
puts(“ The entered line is :”);
puts(str);
}
Output:
Enter a line of text of maximum 49 characters: Hello World
The entered line is:
Hello world

4.6.5 Processing the Strings


The Strings can be processed either by using some predefined functions with help of
string.h header file or by processing all characters individually. Some of the commonly used
predefined functions are
1. int strlen(string_var) – to compute the length of the string, not counting null
characters.
2. strcpy(dst_string,src_string) – to copy a source string into destination string.
3. int strcmp(str1,str2) – to compare str1 with str2.
4. strcat(dst_string,src_string) – to append copy of the source string at the end of
destination string.
Example:
#include<stdio.h>
#include<string.h>
main ()
{
int len1;
char str1[100], str2[100], str3[100], tempstr1[50];
printf(“Enter one string”);
gets(str1);
len1=strlen (str1);
printf(“The length of the string is %d \n”,len1);
strcpy(str2,str1);
printf(“ First string is %s and copied string is %s \n”,str1,str2);
printf(“ Enter the string to be compared with first string:”);
gets(str3);
if (strcmp(str1,str3)==0)
4 .13 | Arrays, Strings and Pointers

printf(“Both strings are equal \n’);


else if (strcmp(str1,str3)<0)
printf(“ First string is lesser than second \n”);
else
printf(“ First string is greater than second string \n”);
printf(“ Enter the string to be concatenated at the right of first string: “);
gets(tempstr1);
strcat(str1,tempstr1);
printf(“ The concatenated string is %s \n”, str1);
}
OUTPUT
Enter one string: Programming
The length of the string is 11
First string is programming and copied string is programming
Enter the string to be compared with first string: Computer
First string is greater than second string
Enter the string to be concatenated at the right of first string: with C
The concatenated string is Programming with C
4.6.6 STRING FUNCTIONS
Function Explanation
strncpy(dest,src,n) Copies up to n characters from src to dest string.
Strncmp(str1,str2,n) Compares str1 and str2 looking at no more than n characters.
Strcmpi(str1,str2) Compare str1 and str2 ignoring the case sensitivity.
Strlwr(str1) Converts string str1 to all lowercase & returns a pointer.
Strupr(str1) Converts string str1 to all uppercase & returns a pointer.
Strncat(dest,src,n) Copies at most n characters of src to the end of dest string.
Memcpy(dest,src,n) Copies a block of n bytes from src to dest
memcmp(str1,str2,n) Compares first n bytes of strings str1 and str2.
Memset(str1,ch,n) Sets first n bytes of array str1 to the character ch.
Strchr(str1,ch) Scans the string str1 for the first occurrence of character ch.
Strset(str1,ch) Sets all characters in the string str1 to the character ch.
Strnset(str1,ch,n) Sets first n characters in the string str1 to the character ch.
Strrev(str1) Reverses all characters in string str1.
Strstr(str1,str2) Scans str1 for the first occurrence of substring str2 and
returns a pointer to starting element.
Itoa(val,str1,radix) Converts the integer val to string str1 using base as radix.
Toi(str1) Converts the string of digits str1 to integer & returns integer.
4 .14 | Arrays, Strings and Pointers

4.7 POINTERS
 A Pointer is a variable. It can contain the memory address of the variable.
 A pointer is a variable that represents the location (rather than the value) of a data
item, such as a variable, an array element, structure.

4.7.1 NEED OF POINTERS:


 They allow you to refer to large data structures in a compact way
 They facilitate sharing between different parts of programs
 They make it possible to get new memory dynamically as your program is running
 Pointers are more efficient in handling Array and Structure.
 Pointer allows reference to function and thereby helps in passing of Function as
Arguments to other function.
 It reduces length and the program execution time.
 They make it easy to represent relationships among data items.

4.7.2 APPLICATIONS OF POINTERS


 Pointers can be used to pass information back and forth between a function and its
reference point.
 In particular, pointers provide a way to return multiple data items from a function via
function arguments.
 Pointers also permit references to other functions to be specified as arguments to a
given function. This has the effect of passing functions as arguments to the given
function.
 Pointer is used in dynamic memory allocation
 Pointer is used for the ease of string manipulations

4.7.3 POINTER DECLARATION:


Pointer variables must be declared before they are being used in C program. When a
pointer variable is declared, the variable name must be preceded by an asterisk(*). This
identifies the fact that the variable is a pointer
SYNTAX:
Datatype *pointername;
 Where datatype - Specifies the type of data to which the pointer points.
 Pointer name – Specifies the name of the pointer.
 When a pointer variable is declared, the variable name must be preceded by an
asterisk (*).
4 .15 | Arrays, Strings and Pointers

Examples
char *c;
int i, *ptri;
float f,*ptrf;

 Within a variable declaration, a pointer variable can be initialized by assigning in the


address of another variable.
 Remember that the variable whose address is assigned to the pointer variable must
have been declared earlier in the program,
 Assigning address to pointer is shown below:

int i;
int *ptr=&i;
 The first line declares i to be integer type variable and the second line declares ptri to
be a pointer variable whose object is an integer point quantity. In addition, the
address of i is initially assigned to ptr as shown in Fig.4.7 below

RAM i 1200 1201

ptr
1200

Fig.4.7: Memory Allocation with pointer reference


Consider the following declaration and assigning address to pointer
int v,*pv;
pv=&v;
The address of v’s memory location can be determined by the expression &v,
where & is a unary operator, called the address operator, that evaluates the address
of its operand.
 Now let us assign the address of v to another variable, pv. Thus,
pv = &v
 This new variable is called a pointer to v, since it “points” to the location where v is
stored in memory.
4 .16 | Arrays, Strings and Pointers

 Pv represents v’s address, not its value. Thus pv is referred to as a pointer variable
shown in Fig 4.8.

Fig.4.8 Relationship between pv and v (where pv = &v and v = *pv)

*pv refers the value of v /content of address stored in pv.


Sample Program to understand pointers
#include<stdio.h>
main()
{
int a=22,*ap;
float b=2.25,*bp;
ap=&a;
bp=&b;
printf(“\n value of a=%d”,*ap);
printf(“\n value of b=%d”,*bp);
}
OUTPUT
Value of a=22
Value of b=2.25

#include<stdio.h>
main()
{
int a=22;
printf(“\n Value of a=%d”,*a);
printf(“\n Address of a=%u”,&a);
printf(“\n Value at address %u=%d”,&a,*(&a));
}
OUTPUT
Value of a=22
Address of a=4000
Value at address 4000=22
4 .17 | Arrays, Strings and Pointers

Sample program to add two numbers using pointers


#include<stdio.h>
void main()
{
int a,b,*ap,*bp, sum;
ap=&a;
bp=&b;
printf(“Enter 2 elements\n”);
scanf(“%d %d”,&a,&b):
sum=*ap+*bp;
printf(“SUM=%d”,sum);
}
Output:
Enter 2 elements
25 34
SUM= 59

ADDITIONAL PROGRAMS

1. Program to find the average of n number


#include<stdio.h>
#include<conio.h>
void main()
{
int num[50],i,size,sum;
float avg;
printf("Enter size of an array\n");
scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&num[i]);
for(i=0;i<size;i++)
sum=sum + num[i];
avg=(float) sum/size;
printf("average=%f",avg);
getch();
}
OUTPUT:
Enter size of an array
4 .18 | Arrays, Strings and Pointers

5
Enter Array elements
20
21
19
18
20
Average=19.600

2. Program to find largest element in a array


#include<stdio.h>
#include<conio.h>
void main()
{
int num[50],i,size,max;

printf("Enter size of an array\n");


scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&num[i]);
max=num[0];
for(i=0;i<size;i++)
if(num[i]>max)
max=num[i];
printf("Largest element;%d",max);
getch();
}
OUTPUT:
Enter size of an array
5
Enter Array elements
45
33
22
60
57
Largest element:60
4 .19 | Arrays, Strings and Pointers

3. Program to sort element in an ascending order


#include<stdio.h>
#include<conio.h>
void main()
{
int num[50],i,j,size,temp;
printf("Enter size of an array\n");
scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&num[i]);
for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
if(num[i]>num[j])
{ temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
for(i=0;i<size;i++)
printf("%d\n",num[i]);
getch();
}
OUTPUT:
Enter size of an array
5
Enter Array elements
33
22
55
11
44
The sorted array:
11
22
4 .20 | Arrays, Strings and Pointers

33
44
55

4. Program to print only even position elements in an array


#include<stdio.h>
#include<conio.h>
void main()
{
int num[50],i,size;
printf("Enter size of an array\n");
scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&num[i]);
for(i=0;i<size;i=i+2)
printf("%d\n”,num[i]);
getch();
}
OUTPUT:
Enter size of an array
5
Enter Array elements
1
2
3
4
5
Even elements
1
3
5

5. Program to find the sum even position element

#include<stdio.h>
#include<conio.h>
void main()
{
4 .21 | Arrays, Strings and Pointers

int num[50],i,size,sum=0;
printf("Enter size of an array\n");
scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&num[i]);
for(i=0;i<size;i=i+2)
sum=sum + num[i];
printf("sum=%d",sum);
getch();
}

OUTPUT:
Enter size of an array
5
Enter Array elements
1
2
3
4
5
Sum of even position=9

6. Program to count the no. of students passed in a subject


#include<stdio.h>
#include<conio.h>
void main()
{
int mark[50],i,size,count=0;

printf("Enter size of an array\n");


scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&mark[i]);
for(i=0;i<size;i++)
4 .22 | Arrays, Strings and Pointers

{ if(mark[i]>=50)
{
count++;
}
}
printf("No.of pass mark:%d",count);
getch();
}
OUTPUT:
Enter size of an array
5
Enter marks
50
55
23
45
78
No. of pass marks:3

7. Program to search an element in an array


#include<stdio.h>
#include<conio.h>
void main()
{
int A[20],i,n,value;
int flag=0;
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter Array elements\n");
for(i=0;i<n;i++)
scanf("%d", &A[i]);
printf("Enter the value to be seacrched\n");
scanf("%d",&value);
for(i=0;i<n;i++)
{
if(A[i]== value)
{ printf("value is found in position:%d\n", i+1);
flag=1;
}
4 .23 | Arrays, Strings and Pointers

}
if(flag==0)
printf("Value not found\n");
getch();
}
OUTPUT:
Enter the size of array
5
Enter Array elements
44
55
66
77
88

Enter the value to be searched


66
value is found in position:3

8. Program to find smallest element in a array


#include<stdio.h>
#include<conio.h>
void main()
{
int num[50],i,size,min;
printf("Enter size of an array\n");
scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&num[i]);
min=num[0];
for(i=0;i<size;i++)
if(num[i]<min)
min=num[i];
printf("Largest element;%d",min);
getch();
}
OUTPUT:
Enter the size of array
5
4 .24 | Arrays, Strings and Pointers

Enter Array elements


44
55
66
77
88
Smallest element: 44

9. Program to copy elements of one array to another


#include<stdio.h>
#include<conio.h>
void main()
{
int A[50],i,size,B[50];

printf("Enter size of an array\n");


scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&A[i]);
for(i=0;i<size;i++)
B[i]=A[i];
printf("First array\n");
for(i=0;i<size;i++)
printf("%d\n",A[i]);
printf("Second array\n");
for(i=0;i<size;i++)
printf("%d\n",B[i]);
getch();
}
OUTPUT:
Enter the size of an array
5
Enter Array elements
44
55
66
77
4 .25 | Arrays, Strings and Pointers

88
First array
44
55
66
77
88
Second array
44
55
66
77
88

10. Program to display the array in reverse order


#include<stdio.h>
#include<conio.h>
void main()
{
int A[50],i,size;

printf("Enter size of an array\n");


scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&A[i]);
printf("Reverse array\n");
for(i=size-1;i>=0;i++)
printf("%d\n",A[i]);
getch();
}
OUTPUT:
Enter the size of an array
5
Enter Array elements
44
55
66
77
4 .26 | Arrays, Strings and Pointers

88
Reverse array
88
77
66
55
44

11. Program to add 2 matrices


#include<stdio.h>
int main()
{
int a[10][10], b[10][10], c1[10][10],r,c, i, j;
printf("\nEnter the row and column size of matrix: ");
scanf("%d%d",&r,&c);
printf("\nEnter First Matrix :");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &a[i][j]);
printf("\nEnter Second Matrix:\n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &b[i][j]);
printf("The First Matrix is: \n");
for (i = 0; i <r; i++)
for (j = 0; j <c; j++)
c1[i][j]=a[i][j]+b[i][j];
printf("\nAddition Of Two Matrices : \n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
printf(" %d ", c1[i][j]);
}
printf("\n");
}
return (0);
}
OUTPUT:

Enter the row and column size of matrix: 3


3
Enter First Matrix :2
2
2
4 .27 | Arrays, Strings and Pointers

2
2
2
2
2
2
Enter Second Matrix:3
3
3
3
3
3
3
3
3
The First Matrix is:
2 2 2
2 2 2
2 2 2
The Second Matrix is :
3 3 3
3 3 3
3 3 3
Addition Of Two Matrices :
5 5 5
5 5 5
5 5 5

12. Program to subtract 2 matrices


#include<stdio.h>
int main( )
{
int a[10][10], b[10][10], c1[10][10],r,c, i, j;
printf("\nEnter the row and column size of matrix: ");
scanf("%d%d",&r,&c);
printf("\nEnter First Matrix :");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &a[i][j]);
printf("\nEnter Second Matrix:\n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &b[i][j]);
for (i = 0; i <r; i++)
4 .28 | Arrays, Strings and Pointers

for (j = 0; j <c; j++)


c1[i][j]=a[i][j]- b[i][j];
printf("\Subtraction Of Two Matrices : \n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
printf(" %d ", c1[i][j]);
}
printf("\n");
}
return (0);
}
OUTPUT:

Enter the row and column size of matrix: 3 3


Enter First Matrix :3
333
333
333
Enter Second Matrix:
222
222
222
Subtraction Of Two Matrices :
1 1 1
1 1 1
1 1 1

13. Program to multiply two matrices


#include<stdio.h>
int main()
{
int a[5][5], b[5][5], c[5][5], i, j, k,r1,c1,r2,c2;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter size of Second Matrix : \n");
scanf("%d%d",&r2,&c2);
if(c1==r2)
{
printf("\nEnter First Matrix : \n");
for (i = 0; i < r1; i++) {
4 .29 | Arrays, Strings and Pointers

for (j = 0; j < c1; j++) {


scanf("%d", &a[i][j]);
}
}
printf("\nEnter Second Matrix:\n");
for (i = 0; i < r2; i++) {
for (j = 0; j < c2; j++) {
scanf("%d", &b[i][j]);
}
}
printf("The First Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
printf(" %d ", a[i][j]);
}
printf("\n");
}
printf("The Second Matrix is : \n");
for (i = 0; i < r2; i++) {
for (j = 0; j < c2; j++) {
printf(" %d ", b[i][j]);
}
printf("\n");
}

//Multiplication Logic
for (i = 0; i < r1; i++) {
for (j = 0; j <c2; j++) {
c[i][j]=0;
for (k = 0; k < c1; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}

}
}

printf("\nMultiplication Of Two Matrices : \n");


for (i = 0; i < r1; i++) {
4 .30 | Arrays, Strings and Pointers

for (j = 0; j < c2; j++) {


printf(" %d ", c[i][j]);
}
printf("\n");
}
}
else
printf("First array col and second array row same!");
return (0);
}
OUTPUT:
Enter size of First Matrix :
2
3
Enter size of Second Matrix :
3
2
Enter First Matrix :
1
1
1
1
1
1
Enter Second Matrix:
2
2
2
2
2
2
The First Matrix is:
1 1 1
1 1 1
The Second Matrix is :
2 2
2 2
2 2
4 .31 | Arrays, Strings and Pointers

Multiplication Of Two Matrices :


6 6
6 6

14. Program to find the transpose of a matrix


#include<stdio.h>
int main( )
{
int a[5][5], b[5][5], r1,c1,i, j;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter elements of Matrix : \n");
for (i = 0; i < r1; i++)
for (j = 0; j < c1; j++)
scanf("%d", &a[i][j]);
printf("The First Matrix is: \n");
for (i = 0; i < r1; i++)
{for (j = 0; j < c1; j++)
printf(" %d ", a[i][j]);
printf("\n");
}
for (i = 0; i <c1; i++) {
for (j = 0; j < r1; j++) {
b[i][j]=a[j][i];
}
}
printf("\nTranspose Matrix is : \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
printf(" %d ", b[i][j]);
}
printf("\n") ;
}
return (0);
}
OUTPUT:
Enter size of Matrix :
2
4 .32 | Arrays, Strings and Pointers

3
Enter elements of Matrix :
2
2
3
4
5
6
The Matrix is:
2 2 3
4 5 6
The Transpose Matrix is :
2 4
2 5
3 6

15. Program to find the sum of all elements in a matrix

#include<stdio.h>
int main()
{
int a[5][5], r1,c1,i, j,sum=0;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter elements of Matrix : \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", &a[i][j]);
}
}
printf("The Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
printf(" %d ", a[i][j]);
}
printf("\n");
}
for (i = 0; i <c1; i++) {
4 .33 | Arrays, Strings and Pointers

for (j = 0; j < r1; j++) {


sum=sum+a[j][i];
}
printf("The Sum of Matrix is : %d",sum);
return (0);
}
OUTPUT:
Enter size of Matrix :
2
2
Enter elements of Matrix :
3
3
3
3
The Matrix is:
3 3
3 3
The Sum of Matrix is : 12

16. Program to print only upper triangle matrix

#include<stdio.h>
int main( )
{
int a[5][5], r1,c1,i, j;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter elements of Matrix : \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", &a[i][j]);
}
}
printf("The Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
4 .34 | Arrays, Strings and Pointers

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


}
printf("\n");
}
printf(“Upper matrix:\n”);
for (i = 0; i <c1; i++) {
for (j = 0; j < r1; j++) {
if(i<=j)
printf("%d\t",a[i][j]);
}
printf("\n");
}
return (0);
}
OUTPUT:

17. Program to display the identity matrix


#include<stdio.h>
int main( )
{
int a[5][5], r1,c1,i, j;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
if(i==j)
a[i][j]=1;
else
a[i][j]=0;
}
}
printf("The Identity Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
printf(" %d ", a[i][j]);
}
printf("\n");
}
return (0);
}
4 .35 | Arrays, Strings and Pointers

OUTPUT:
Enter size of First Matrix :
3
3
Enter elements of Matrix :
2
3
4
1
2
6
7
4
5
The Matrix is:
2 3 4
1 2 6
7 4 5
Upper matrix:
2 3 4
0 2 6
0 0 5

18. Program to display the lower triangle matrix


#include<stdio.h>
int main( )
{
int a[5][5], r1,c1,i, j;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter elements of Matrix : \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", &a[i][j]);
}
}
printf("The Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
4 .36 | Arrays, Strings and Pointers

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


}
printf("\n");
}
printf(“lower matrix:\n”);
for (i = 0; i <c1; i++) {
for (j = 0; j < r1; j++) {
if(i>=j)
printf("%d\t",a[i][j]);
}
printf("\n");
}
return (0);
}
OUTPUT:
Enter size of First Matrix :
3
3
Enter elements of Matrix :
4
5
6
4
8
9
7
6
5
The Matrix is:
4 5 6
4 8 9
7 6 5
Lower matrix:
4 0 0
4 8 0
7 6 5

19. Program to display the matrix with only diagonal


4 .37 | Arrays, Strings and Pointers

#include<stdio.h>
int main( )
{
int a[5][5], r1,c1,i, j;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter elements of Matrix : \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", &a[i][j]);
}
}
printf("The Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
printf(" %d ", a[i][j]);
}
printf("\n");
}
printf(“Diagonal elements :\n”);
for (i = 0; i <c1; i++) {
for (j = 0; j < r1; j++) {
if(i==j)
printf("%d\t",a[i][j]);
else
printf(“\t”);
}
printf("\n");
}
return (0);
}
OUTPUT:
Enter size of Matrix :
3 3
Enter Element of Matrix :
5
6
4
4 .38 | Arrays, Strings and Pointers

3
2
5
7
6
5
Matrix is:
564
325
765
The Diagonal Element of Matrix is:
5
2
5
20. Program to find the length of string without string functions

#include<stdio.h>
#include<conio.h>
void main( )
{
char s[20];
int i;
printf("Enter the string\n");
scanf("%s",s);
i=0;
while(s[i]!='\0')
i++;
printf(" No. of characters:%d", i);
getch();
}
OUTPUT:
Enter the string
Apple
No. of characters:5
21. Program to find the length of string using string functions

#include<stdio.h>
#include<conio.h>
4 .39 | Arrays, Strings and Pointers

void main( )
{
char s[20]; int i;
printf("Enter the string\n");
scanf("%s",s);
i=strlen(s);
printf(" No. of characters:%d", i);
getch();
}
OUTPUT:
Enter the string
Apple
No. of characters:5
22. Program to copy a string
#include<stdio.h>
#include<conio.h>
void main( )
{
char s1[20],s2[20];
printf("Enter the string\n");
scanf("%s",s1);
strcpy(s2,s1);
printf("Copied string: %s", s2);
getch();
}
OUTPUT:
Enter the string
Lord
Copied string :Lord

23. Program to copy a string without using string functions

#include<stdio.h>
#include<conio.h>
void main( )
{
char s1[20],s2[20];
printf("Enter the string \n");
4 .40 | Arrays, Strings and Pointers

scanf("%s",s1);
for(int i=0;s1[i]!='\0';i++)
s2[i]= s1[i];
printf("Copied string: %s", s2);
getch();
}
OUTPUT:
Enter the string
Lord
Copied string :Lord

24. Program to concatenate 2 strings


#include<stdio.h>
#include<conio.h>
void main( )
{
char s1[20],s2[20];
printf("Enter the WORD1\n");
scanf("%s",s1);
printf("Enter the WORD2\n");
scanf("%s",s2);
strcat(s1,s2);
printf("CONCATINATED STRING:%s", s1);
getch();
}
OUTPUT:
Enter the WORD1
GOOD
Enter the WORD2
GIRL
CONCATINATED STRING: GOODGIRL
25. Program to compare two strings
#include<stdio.h>
#include<conio.h>
void main( )
{
char s1[20],s2[20];
printf("Enter the WORD1\n");
scanf("%s",s1);
4 .41 | Arrays, Strings and Pointers

printf("Enter the WORD2\n");


scanf("%s",s2);
if(strcmp(s1,s2)==0)
printf("Both strings are equal\n");
else if(strcmp(s1,s2)>0)
printf("S1 is greater than S2\n");
else
printf("S2 is greater than S1\n");
getch();
}
OUTPUT:
Enter the WORD1
GOOD
Enter the WORD2
GIRL
S1 is greater than S2
26. Program to reverse a string
#include<stdio.h>
#include<conio.h>
void main( )
{
char s1[20],s2[20];
int i=0,len;
printf("Enter the WORD1\n");
scanf("%s",s1);
while(s1[i]!='\0')
i++;
len=i;
for(i=len,j=0;i>=0;i--,j++)
s2[j]=s1[i];
printf("Input :%s", s1);
printf("Output:%s", s2);
getch();
}
OUTPUT:
Enter the WORD1
bin
Input :bin
Output :nib
4 .42 | Arrays, Strings and Pointers

27. Program to sort strings


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char word[50][20],temp[20];
int i,j,n;
printf("Enter the number of words”);
scanf("%d",&n);
printf(“Enter the words”);
for(i=0;i<n;i++)
scanf("%s",word[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{ if(strcmp(word[i],word[j])>0)
{
strcpy(temp,word[i]);
strcpy(word[i],word[j]);
strcpy(word[j],temp);
}
}
printf(“Sorted strings:”);
for(i=0;i<n;i++)
printf("%s\n",word[i]);
getch();
}
OUTPUT:
Enter the number of words
5
Enter the words
red
blue
white
black
pink
Sorted strings:
black
blue
4 .43 | Arrays, Strings and Pointers

pink
red
white

28. Program to calculate the area of circle using pointers


#include<stdio.h>
#include<conio.h>
void main( )
{
float radius, area;
float *p=&radius;
printf(“Enter the radius\n”);
scanf(“%f”,p);
area=3.14 * (*p) * (*p);
printf(“Area=%f”,area);
getch();
}
OUTPUT:
Enter the radius
4.5
Area=63.585
29. Program to calculate the distance between two points
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int x1,x2,y1,y2,*a,*b,*c,*d, dist;
a=&x1;
b=&x2;
c=&y1;
d=&y2;
printf("Enter the first point");
scanf("%d %d",a,c);
printf("Enter the second point");
scanf("%d %d",b,d);
dist=sqrt((((*a)-(*b))*((*a)-(*b)))+(((*c)-(*d))*((*c)-(*d))));
printf("Distance=%d",dist);
getch();
}
4 .44 | Arrays, Strings and Pointers

OUTPUT:
Enter the first point
8 10
Enter the second point
5 6
Distance= 5

30. Program to perform arithmetic operations using pointers


#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,opt,result;
char ch;
int *p1,*p2;
p1=&num1;
p2=&num2;
printf("Enter two numbers\n");
scanf("%d %d",p1, p2);
do
{
printf("Choose the option(1-5) from the following menu\n");
printf("1.Addition\n");
printf("2.Subtraction\n");
printf("3.Multiplication\n");
printf("4.Division\n");
printf("5.Modulus\n");
printf("6.Exit\n");
scanf("%d",&opt);
switch(opt)
{
case 1: result=*p1+*p2;
break;
case 2: result=*p1-*p2;
break;
case 3: result=*p1* *p2;
break;
case 4: result=(*p1)/(*p2);
break;
case 5: result=(*p1)%(*p2);
4 .45 | Arrays, Strings and Pointers

break;
case 6: exit(0);
break;
}
printf("Result=%d",result);
}while(opt<=5);
getch();
}
OUTPUT:
Enter two numbers
67
Choose the option(1-5) from the following menu
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.Exit
3
Result=42
Choose the option(1-5) from the following menu
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.Exit
6
4 .46 | Arrays, Strings and Pointers

You might also like