Beruflich Dokumente
Kultur Dokumente
M ARRAYS
5.1.1. Introduction
> For storing a single data item programmers uses variables; but in many
application, programmers need to store a large amount of data, thus for storing
large amount of data we need to declare large number of variable which is not
convenient. And these variables are independent and not related with each other,
so for storing large amount of data C provides the concepts of Array.
> Array means collection. An array is used to store elements of the same type. It is
a very popular and useful data structure and stores data elements in contiguous
locations. More than one element is arranged in sequence so it is also called a
composite data structure.
> Array is a linear and homogenous data structure. Homogenous means that the
same types of elements are stored in it.
or
An array is a homogenous, fixed-size sequenced collection of elements of the
same data type which are allocated contiguously in the memory.
> Following figure shows the concept of array where the lowest address
corresponding to the first element and the highest address to the last element.
First Element Last Element
1 ___________________________________!
Numbers[0] Numbers[l] Numbers[2] Numbers[3]
Benefits of Arrays
1) They are used to represent all sorts of lists.
2) They are used to implement other data structures such as stacks, queues, heaps,
etc.
Limitations of Arrays
1) The prior knowledge of number of elements in the linear array is necessary.
2) These are static structures. Static in the sense that, whether memory is allocated
at compilation time or runtime, their memory used by them cannot be reduced or
extended. Since the elements of these arrays are stored in consecutive locations,
the insertions and deletions in these arrays are time consuming. This is because
of moving down or up to creates a space of new element or to occupy the space
vacated by the deleted element becomes complex in array of large elements size.
5.1.2. Characteristics of Arrays
1) Array elements are stored in successive memory locations.
2) Once array is declared, its lowest bound cannot be changed, but the upper bound
can be expanded with the compiler. The array name itself is a constant pointer
and user cannot modify it. Therefore, the lowest bound of an array cannot be
expanded.
3) Array name itself is a pointer.
4) All the elements of an array share the same name, and they are different from
one-another with the help of the element number.
5) Amount of memory required for an array depends upon the data type and the
number of elements.
Total bytes = size of (data type)* size of array
6) Once an array is created, we cannot remove or insert memory locations. An
element can be deleted or replaced but the memory location remains as it is.
7) Once an array is declared and not initialized, it contains garbage values.
8) If we declared an array as a static (predefined keyword) then all the elements are
initialized to zero.
The linear arrays are also called one-dimensional arrays, since each element in the
array is referenced by a single subscript. The one dimensional array is the array in
which the elements are represented in single row (figure 5.1).
arr[0] arr[l] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7] arr[8] | arr[9]
I 4 I I I. I I II I
50 70 93 83 33 44 77 88 99
t
1
o
U)
Name
of
the
arra
Array index
Values (of memory
y
location) Figure 5.1
5.2.2. Declaration & Initialization of One Dimensional
Array
Consider the following code that initializes while declaring array
i) int codes[10] = {1, 2, 3,4, 5, 6, 7, 8, 9, 10};
ii) int codes[10] = {1,2};
iii) int codes[10];
Explanation
> In the first statement, codes array is an ‘integer array of ten elements’, which has
10 elements initialized with values ranging from 1 to 10.
> In the second statement, the first two of the codes array are set to 1 and 2, and the
rest 8 values are left blank. The last statement does not initialize anything. If you
do not initialize the array then it will be full of junk/garbage items.
> In the third statement, all the values of the codes array are initialized to 0.
Explanation: The first thing new is the line that defined a “char” type of data entity.
The square brackets define an array subscript in C, §nd in the case of the data
definition statement, the 4 in the brackets defines 4 data fields of type “char” all
defined as the variable “name”.
In the C language, all subscripts start at 0 and increase by 1 each step up to the
maximum which in this case is 3. We, therefore, have 4 “char” type variables named,
“name[0]”, “name[l]”, “name[2]”, and “name[3]”. In C, the subscripts actually go
from 0 to one less than the number defined in the definition statement.
int myRamp[100];
int i;
for(i = 0; i < 100; i++)
{
myRamp[i] = i; //This is same as f(x) = x
}
Program 2: To initialize an array.
#include<stdio.h>
#include<conio.h>
main()
{
int i[4]={l,2,3,4}, j;
clrscr();
printf("The elements in array after initialization");
for(j=0; j<=4; j++)
{
i[j] =j;
printf("\n i[%d] = %d",j, i[j]);
}
getch();
}
Output
PI DOSBor 074, Cpu speed: «ax 100t cycles Raneskip 0 rn.p
r
flfiaents in arrau p initial iwt inn
a-' 0
HI] - 1 ’ r 2 ] - 2 'jp•;"
For example, given the marks in an array the first element is accessed as:
marks [0]
To process all the elements^ in marks, a loop similar to the following code is used:
> Here is the section of code that places data into an array to displaying output: for
The for loop causes the process of asking for and receiving a student’s marks from
the user to be repeated 30 times. The first time through the loop, i has a value 0, so
the scanf() statement will cause the value typed to be stored in the array element
marks[0], the first element of the array.
This process will be repeated until i becomes 29. This is last time through the
loop, because there is no array element like marks[30].
In the scanf() statement, we have used the “address of’ operator (&) on the
element marks[i] of the array. In so doing, we are passing the address of this
particular array element to the scanf() function, rather than its value; which is
what scanf() requires.
#include<stdio.h>
#include<conio.h> '
void main()
{
int i[4]; int j; int Addition=0;
clrscr();
printf("enter the values for addition & press enter key after entering each value:
");
for(i=0;i<10;i++)
{
if(item==array[i])
{
flag=i;
break;
}
}
if(flag>=0)
printf("\n %d is found at the position %d", item, flag+1);
else
printf("\n item does not found");
getch();
}
Output
Elements could be added either at the end of the array or at any user defined position.
Adding the element at the end of the existing array is very simple’Bin to insert an
element at a user defined position calls for little more efforts. From the position to the
end; the element has to be pushed-down while adding an element at the end of array.
The following program shows insertion into an array.
}
5.2.4.4. Deletion from an Arrav
Because an array is a contiguous storage of element, the deletion of an element has
to be dene with a bit of caution. When an element in an array is deleted (provided, it
is not being the last element) it is required to be rearranged so that no holes are
present in it and array size has to be marked accordingly.
Program 7: To illustrate the deletion from an Array.
#include<stdio.h> ’
int array[15] = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int
array_size = 10; //'array is initialized to 0.
void remove_at (int position)
{
int i;
for(i = position; i < array_size-l; i++)
array[i] - array[i + 1]; // deletes the element at that position .
array[array_size-lj = 0;
array _ size = array_size-1; //reduces the array size by 1 void
void delete_all(int
element) {
int i;
for(i = 0; i < array_size;
i++) if (array[i]==element)
remove_at(i); //deletes every occurrence of the element
}
void main(void)
{
int element, i; clrscr();
printfO'Enter the element to delete (only first occurrence): ); scanf("%d",
&element); .
delete_first(element); ^
printf("Enter the element to delete (all occurrence):"); scanf("%d", &element);
delete_all(element);
for(i = 0; i < 15; i++)
printf("%d\n", array [i]);
5.2.4.5. Sorting Arrays
> Sorting is the process of arranging the elements in some logical order. I his
logical order may be ascending or descending in case of numeric values or
dictionary order in case of alphanumeric values.
> There can be three classes of algorithms according to the memory
requirements.
i) Sort in place and use no extra memory except perhaps for a small stack or
table.
ii) Algorithm that use a Jinked-list representation and so use N extra words
of memory for list pointers.
iii) Algorithms that need enough extra memory space to hold another copy of the
array to be sorted.
Algorithm: Bubble Sort
Sorts an Array A with N elements.
BUBBLE_SORT (A, N)
Step 1: Initialization Set I =0
Step 2: Repeat step 3 to 5 Until I < N
Step 3: Set J = 0
Step 4: Repeat Step 5 until J < N - i -1 Step 5: If A[J] > A[J+1] then Set temp =A[J]
Set A[J]
Set A[J] = A[J+1]
Set A[J+l]=Temp End If
Step 6: Exit
The algorithm is straightforward. Before each pass, the interchange marker is
initialized to zero. This marker is incremented each time an interchange is made. If at
the end of a pass, marker has a value of zero, the sort is complete.
Program 8: To illustrate the bubble sort.
#include<stdio
,h> void main()
{
int A[20], N, Temp, i, j; clrscr();
printf(“\n\n\t ENTER THE NUMBER OF TERMS
scanf(“%d”,&N);
printf(“\n\t ENTER THE ELEMENTS OF THE ARRAY.
for(i=0; i<N; i++)
{ . gotoxy(25, 11+i);
scanf(“\n\t\t%d”,
&A[i]);
}
for(i=0; i<N-l; i++) for(j=0; j<N-i;j++) if(A[j]>A[j+l])
'{
Temp = A[j];
A[j] = A[j+1];
A[j+1] = Temp;
}
printf(“\n\tTHE ASCENDING ORDER LIST IS... An”);
for(i=0; i<N; i++)
printf(“\n\t\t\t%d”,A[i]);
getchO;
for(i=0;i<=9;i++)
printf(" %d\t" ,arr[i]);
getch();
}
void quicksort(int a[],int lower,int upper)
{
int i;
if(upper>lower)
{
i=split(a,lower,upper);
quicksort(a,lower,i-1);
quicksort(a,i+1,upper)
;
}
}
int splk(int a[],int lower,int upper)
{
int i,p,q,t; p=lower+l; q=upper; i=a[lower];
while(q>=p)
{
while(a[p]<i) ,
p++;
while(a[q]>i
)
q--;
if(q>p)
{
t=a[p]; a[p]=a[q]; a[q]=t;
}
}
t=a[lower]; a[lower]=a[q]; a[q]=t; return
q;
}
Output
ujmyuimwww
5.3. ARRAYS AND FUNCTIONS
5.3.1. Introduction
A function is a self-contained program segment that carries out some specific, well-
defined task. Every C program consists of one or more functions. One of these
functions must be called main. Execution of the program will always begin by
carrying out the instructions in main. Additional functions will be subordinate to
main, and perhaps to one another.
In C, one cannot pass entire array as an argument to a function. One can, however,
pass a pointer to an .array by specifying the array’s name without index. For
example, the following program fragment passes the address of I to funcl():
int main()
{ . int i[10]; funcl(i);
}
If a function receives a pointer to a single- dimension array, you can declare its formal
parameter in one of three ways: as a pointer, as a sized array, or as an unsized array.
For example, to receive i, a function called funcl() can be declared as
void fund (int *x)
{
}
Or
void fund (int x[10])
{
}
Or
void fund (int x[])
{
}
All three declaration methods produce similar result because each tells the compiler
that an integer pointer is going to be received.
Types of Array Passing
The array elements can be passed to a function in two ways:
1) Call by value,
2) Call by reference.
5.3.2. Passing Array Using Call by Value
In the call by value method, one passes values of array elements to the function.
Program 10: Passing of an array element of one dimension to a function using
call by value mechanism.
#include<stdio.h>
#define SIZE 10
int isEven(int k);
void main()
{
int arr[SIZE]={ 12,15,20,17,25,50,11,10,38,13}; int i; clrscr()‘
printf("\t ******* CHECKING FOR EVEN OR ODD NUMBER BY
. USING CALL BY VALUE *******\n"); for(i=0;i<SIZE;i++)
{ ' if(isEven(arr[i]))
{
printffNUMBER %d IS EVEN",arr[i]);
}
else
{
printf("NUMBER %d IS ODD",arr[i]);
}
printf("\n");
}
getch();}
/*function to check whether the argument is even number*/
-1. int isEveu(int k) ' :: .*•" • ' ■ ' ■ .** ' '
• ■> ' ■
if(k%2==0) return k; else
return 0;}
Since arrays are passed by reference this means that if the function changes the value
of an element in an array that is a parameter of the function then the corresponding
actual array of the call will have that element changed.
void main()
{
float arr[SIZE]={ 12,15,20,17,25,50,11,10,8,13};
int i;
clrscrQ;
for(i=0;i<SIZE;i++)
modify(&arr[i]);
printf("\n\n\n ELEMENTS OF ARRAY AFTER MODIFICATION
\n\n");
for(i=0;i<SIZE;i++) printf(" %.2f',arr[i]); printf("\n");
getch(); .
}
{
*p+=*p*.l;
Output
#include<stdio.h>
void main()
{
}
int num[5],i;
void add(int[]);
clrscr();
printf("\t ******** SUM USING CALL BY REFRENCE
printf(" ELEMENTS OF ARRAY ARE:\n"); for(i=0;i<5;i++)
{
printf( ' NUMBER %d IS : ",i + 1);
scanf(" %d", &num[i]);
}
add(num);
getch();
}
void add(int *num)
{
int sum=0,i;
printf("\nll— ....... .........- ........... - ------------- --------------------------------- ll\n\n");
for(i=0;i<5;i++)
sum += num[i];
printf(" SUM OF 5 NUMBERS = %d \n",sum);
}
Output
k ■ fX)fjfk>x 0.74, C.pu speed: max 100% cycles. Frairaeskip 0. Program:
~~ «««««* SUM USING CALL BY REFBEMCE ******.
SUM OF 5 NUMBERS = 25
0!2
n-2n-1
Here a[j][k] denotes the element in the jth row and kth column.
> Two-dimensional arrays are called matrices in mathematics and tables in
business applications; hence two-dimensional arrays are sometimes called
matrix arrays.
> A two-dimensional array differentiates between the logical and physical view of
data. A 2-D array is a logical data structure that is useful in programming and
problem-solving. For example, such an array is useful in describing an object
that is physically two-dimensional such as a map or checkerboard.
Syntax
type variable_name[number of rows][number of columns];
For example,
int a[5][5];
Here ‘a’ is the name of the array of type int of size 5 by 5. The array elements are
a[0][0], a[0][l] ......... .. a[4][4],
Syntax
type array_name[row_size][column_size] = {array_elementl,
array_element2................ array_element_n}
For example, consider the following matrix which shows the case where A has 3
rows and 4 columns. Each row contains those elements with the same first subscript,
and each column contains those elements with the same second subscript.
Columns
1 2 3 4_
1 p A[l, 1] A[l, 2] A[l, 3] A[l, 4]
Row 2 A[2, 1] A[2,2] A[2,3] A[2,4]
3 l_A[3,l] A[3,2] A[3,3] A[3,4]
Figure 5.3: 2-Dimensional 3x4 Array A
Figure 5.4
Here, s denotes student array with the marks of students.
One can easily refer to the marks obtained by the third student using the subscript
notation as shown below:
printf ("Marks of third student = %d", stud[2][l]);
• Index
Similarly, for the column major order representation, let us consider the same matrix.
, -- ►Address
f ( f f
1(1.1) 2(1,2) 3(1,3) 4(1,4) 5(2,1) 6(2,2) 0 1 2 3 4 5 6 7 8 9 10 11
7(2,3) 8(2,4) 9(3.1) 10(3,2) 11(3,3) 1 5 9 2 6 10 3 7 11 4 8 12
12(3,4) Matrix
100 10 10 10 10 110 112 11 116 11 120 122
Representation 2 4 6 8 4 8
Data r>-
Index
int main ()
/* an array with 5 rows and 2 columns */ int
a[5][2] = {{0,0}, {1,2}, {2,4}, {3,6},{4,8}}, inti,
j;
a[i][j]);
}
}
getch();
}
Output _____ ________________________________ — ----- --- s
----- ------ V/
i C:\ll se rsvpra veshVDes ktop\t\bitwi se.exe
[0][0] = 0 -
[0][13 0 *
[1310] - 3
[11C13 = 2
[2 3[03 - 2
[23113 = 4
[3 3[03 - 3
133 Cl =
1
343[03 4
<>
= 8
Row, Col. A[0][0] A[0][1] A[0][2] A[1][0] A[l][ll A[l][2] uciueni [S Ar2ir2i
A[2][0] A[2][l]
9
Value 1 2 3 4 5 6 7 8
Address 4052 * 4054 4056 4058 4060 4062 4064 4066 4058
iOilVIENSIONAL ARRAYS
C also provides the concept of array of three or more dimensions, is called subs^pts
nS1°nal The multidimensional arraY is controlled by multiple
The element of B with subscripts Kx, K2, .. ..Kn will be denoted by,
Bkl.k2.-kn or B[Ki, K2,...KN]
a2 can be printed out with a similar pair of nested loops: for(i = 0; i < 5; i = i + 1)
{ . . for(j = 0; j < 7; j = j + 1)
printf("%d\t",
a2[i][j]); printf("\n");
\« .
The “row” and “column” subscripts can be explicitly print. for(j = 0; j <7; j = j + 1)
printf("\t%d:", j); printf("\n");
for(i = 0; i < 5; i = i + 1)
{
printf("%d:", i); •
for(j = 0 ; i < 7 ; j = j + 1)^' '*~
printf("\t%d", a2[i][j]);
printf("\n");
}
This fragment would print:
0: 1: 2: 3: 4: 5: 6:
0: 0 1 2 3 4 5 6
1: 10 11 12 13 14 15 16
2: 20 21 22 23 24 25 26
3: 30 31 32 33 34 35 36
4: 40 41 42 43 44 45 46
Program 16: Read the quantity and rate of certain items using
multidimensional array. Calculate total cost by multiplying quantity and rate
and offer 2% discount on it and display the net amount.
# include<stdio.h>
# include<conio.h>
main ()
{
long m[2] [2] [2] [2];
m[a] [b] [c] [d]=m[a-1 ] [b] [c] [d] *m[a-1 ] [b] [c] [d+1];
m[a] [b] [c] [d+1 ]=m[a-1 ] [b] [c] [d] *m[a-1 ] [b] [c] [d+1 ]*2/l 00;
}
}
printf(" ___________
||==================================:=== ---------------------------------------
==ll\n");
getch();
Output
DOSBox G 74. Cpu speed: max 100% cycles, rtameskip 0, Procram
Explanation
In the above example the four-dimension array m[2] [2] [2] [2] is declared. The first
four for loops are used to read the quantity and rate. The values of variables
t . tlmes remains zero where as values of ‘b’ and ‘c’ changes to 1 (0,0), 2 (0,1) 3 (1,0)
and 4 (1,1). This happens during execution of for loops. The’ if statement checks as to
whether the value of a==0 or not. As long as its value is zero reading operation is
performed. When it is greater than zero, rate and quantity are multiplied for obtaining
the amount. Also discount is calculated. Amount and discount are stored in the array
m[2] [2] [2] [2], Net amount is printed after subtracting discount from gross amount.
5,6 STRINGS
5.6.1. Definition and Concepts
> A string is a sequence of symbols that are chosen from a set of alphabet. A string
is, essentially, a sequence of characters.
> A string is generally understood as a data type storing a sequence of data values,
usually bytes, in which elements usually stand for characters according to a
character encoding, which differentiates it from the more general array data type.
> Strings in C are represented by arrays of characters. The end of the string is
marked with a special character, the null character, which is simply the character
with the value 0. For example, we can declare and define an array of characters,
and initialize it with a string constant:
char string[] = “Hello, world!”;
> String are used to suggest strings in which the stored data does not (necessarily)
represent text.
> A variable declared to have a string data type usually causes storage to be
allocated in memory that is capable of holding some predetermined number of
symbols.
> When a string appears literally in source code, it is known as a string literal and
has a representation that denotes it as such.
For example,
char unit;
unit = ‘F’ ; /* for Fahrenheit */
The data type here is char, the name of the array is chararray, and n is the number of
elements.
For example, consider the following declaration and allocation of storage for a
character array that can hold 10 characters, char chararray [10];
chararray[0] = ‘a’;
chararray[l] = ‘x’;
chararray [2] = ‘c’;
chararray [3] = ‘b’;
chararray [4] = T;
chararray[5] = ‘k’;
chararray[6] = ‘m’;
chararray[7] = ‘d’;
chararray[8] = ‘g’;
chararray[9] = T;
Here m above example 10 characters are stored in this array chararray. As with any
array these characters can only be accessed individually.
Example: Initialization of a string must have the following form, (this is similar to
initializing a one-dimensional array):
charmonthlf] = { ‘J’, ‘a’, ‘n\ ‘u\ ‘a’, V, y, ‘\0’};
Then the string month is initialized to January. This is perfectly valid but C
offers a special way to initialize strings. The above string can be initialized as:
char month 1[] = “January”;
The characters of the string are enclosed within a pair of double quotes. The compiler
takes care of storing the ASCII codes of the characters of the string m memory and
also stores the null terminator in the end.
It is a one-dimensional array. Each character occupies a byte. A null character C\0’)
that has the ASCII value 0 terminates the string. Figure 5.9 shows the storage of the
string January in the memory. Recall that \0 specifies a single character whose ASCII
value is zero.
Character string .
terminated by a ^ null
character “\0”
\0
Figure 5.9: String Stored in a String Variable Month
Number of literals must match the number of elements in the array. If too few literals
are specified, the rest of the array is filled with blank characters. Also, a number being
stored in a char array must be specified as individual digits.
Program 17: Demonstrating String.
#include<stdio.h>
int main()
{
char stmame[15];
printf(“Enter the string:\n”);
scanf(“%s”, stmame);
printf(“\n The string entered is: %s\n”, stmame);
return 0;
Explanation:
stmame
s t r i n g & g g g g g g f! £ ‘\0’
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The function strlen() returns an integer that is the count of the number of characters in
the string including embedded blanks and excluding the null terminator. Program 18
shows the use of this function.
Syntax
strlen(String);
Program 18: Finding String Length Using strlen() Function
#include<stdio.h> »
#include<conio.h> ■
#include<string.h> int main()
n = strlen(stmamel);
printf("The number of characters in stmamel is: %d\n", n);
n = strlen(stmame2); ^
printf("The number of character in stmame2 is: %d\n", n);
n = strlen("MOBILECCOMMERCE");
return 0;
strcpyO Function . . . ,
The function strcpyO is used to copy one string to another that is, it copies o one
variable of string type to another variable of string type.
Syntax
strcpy(Stringl, String2);
Note: To allocate string2 big enough to hold the string that would be copied to it. Also, at the top of
any source file where we’re using the standard library’s string-handling functions (such as strcpy)
we must include the line #include<string.h> which contains external declarations for these
functions.
Explanation: The first call to printf prints “_THAKUR_”, and the second one prints
“_PUBLICATIONS_” indicating that the contents of string6 have been tacked on to
the end of string5. The string5 is declared with extra space, to make space for the
appended characters.
Syntax
strncat(sl, s2, n);
Program 21: String Concatenation by Using strcat() and strncat() Function.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() '
{
char si[80], s2[10];
int n;
clrscrQ;
printf("Enter two strings:");
scanf("%s%s", si, s2);
strcat(sl, s2);
printf("\nString built by strcat is %s.", si); printf("\nLength of the
string built by strcat is %d.", strlen(sl));
Explanation: When the above program is provided with inputs ‘thakur’ and
‘publishers’, the string built by strcat() is ‘thakurpublishers’ and the length of the
string is 16. After strncat() is used, the result in si is ‘thakurpublisherspubli’.
In this case, the character strings stmgl and stmg2 are compared character-by-
character. When unequal characters are found the order of the two strings is
determined. Based on the order of the two strings the comparison generates the
following results:
1) k > 0 positive number i.e., (stmgl after stmg2)
2) k = 0 positive number i.e., (stmgl identical to stmg2)
3) k < 0 negative number i.e., (stmgl before stmg2)
Note: The strcmpO function does not return a Boolean, true/false, zero/nonzero answer; it
gives 0 as an output if the strings are equal else returns the difference in their ASCII codes.
Syntax
strupr(stl);
Program 25: Changing String to Uppercase Using strupr() Function.
#include<stdio.h> f
#include<conio.h>
#include<string.h>
void main()
{
char str 1 [31 ]; clrscr();
printf("Enter any string of length <= 30:"); gets(strl);
printf("\nString after conversion: %s\n", strupr(strl));
}
Output
■ DGSBox 0 74. Cpu speed: mas 100%cycles. Frameskip 0. Program: TC BMP
Enter any string of length <= 30:publication
String after conversion: PUBLICATION
Explanation: Here, the first string passed to strstr is, Welcome to C programming
world!. The second string is C. The function searches the first string for the given
second string. Though there are one instances of C in the first string, so it is
considered, and a pointer to the beginning of the match is returned.
Output
Explanation: ASCII value of ‘A’ is 65 while ‘a’ is 97. Difference between them is
97 - 65 = 32
So if we will add 32 in the ASCII value of ‘A’ then it will be ‘a’ and if will we
subtract 32 in ASCII value of ‘a’ it will be 'A'. It is true for all alphabets.
5.8. PROGRAMS
Program 34: Find highest and lowest element in a single dimension array.
#include<stdio.h>
#include<conio.h>
void main()
{
int arraytSl^maXjinin; clrscr();
printf("\t ******* MAXIMUM & MINIMUM ELEMENT OF ARRAY
void main()
{
int a[20], n, i, j, c, max, min; unsigned long prod; clrscr();
printf("\t\t****** LCM & GCD OF ELEMENTS OF ARRAYS ******\n\n");
printf("\tEnter the count of numbers: ");
scanf("%d",&n); ,
printf("\n\n\tEnter the entries: \n");
for(i=0;i<n;i++)
{ . scanf("%d",&c);
if(c>0) ..
a[i]=c;
else
{
printf(”Invalid Entry"); return;
}
}
max=a[0]; for(i=0;i<n;i++) if(a[i]>=max)
max=a[i];
min=a[0]; =
for(i=0;i<n;i++) if(a[i]<min) min=a[i];
for(i=0,prod=l ;i<n;i++) prod=prod*a[i];
for(i=max;i<=prod;i+=max)
{
c=0;
for(j=0;j<n;j++)
if(i%a[j]=0)
c+=l;
if(c==n) __
{ ' ' " printf("\tThe LCM of the nos:
%d\n",i); break;
}
} , for(i=min;i>0;i—)
{
if (min%i==0)
{
c=0;
for(j=0;j<n;j++)
if(a[j]%i==0)
c+=l;
}
if(c==n)
{
printf("\tThe GCD of the nos: %d\n",i);
break;
}
1
} ^ getch();
}V
Output
SDl_app
****■*•«• LCM « GCD OF Ef.EMEM
Enter- the count of numbers: 3
Program 36: Menu Driven Program for encoding and decoding of String.
#include<stdio.h>
#include<conio.h>
#include <string.h>
* int main() {
for(Index=0;Index<strlen(String2);Index++)
{
String3[Index]=String2[Index]-1 ;//decoding
}
printf("\nThe Decoded String is:\n\n"); pubs.String3);
geteh* K return 0;
S
J
Output
CADev- CppXExam plesW.
for(i=0;i<rl;i++)
{
for(j=0;j<c 1 ;j++)
printf("%d\t",A[i][j]);
printf("\n");
}
• „ printf("Enter rows and columns of B matrix \n");
printf("Again row wise\n");
for(i=0;i<r2;i++)
{
tO uinpj :()qoj3§ {
:(„3uop aq jouubo uopBoijdpinp^ xujBpvJjjuud
}
asp
{
{
X„u\„)jjuud
{
X[f]M3‘uJ\P%.,)jJupd
{
/* ■ to] [3] a* [z\ [0]v+[o] [ 1 ] a* [ 1 ] to] v+fo] to] a* to] [oJv=[o]
toto*/
i[nwa*MMv=+tnmD
}
(++*IJ>5I:O=51)-TOJ
;0=[f][?]D
}
(++[^o>po=DJOJ
}
(++i:ij>i:o=i)jqj
{
% i(„n\.,)fl«pd
i([n[i]a‘„J\P%,.)jJaud
(++f^3>f;o=f)-I0i
}
(++T‘2I>T‘0==T)JOJ
t^uysMoijoj sb g xujbui aqj paiajua 3ABq noj^Jjjuud
{
i([Q[T]av‘,.p%,.)jo8os
(++r.£3>no=0°j
}
Output
• C:\Dev-Cpp\Examples\VTU C\matrix_multiply,exe
nter nunber of rows and coiunns of matrix A
int main() {
int i, j, k, n, min, max, matrix[ROW][COL], pos[2][2];
/* get the order of the matrix from the user */
printf("Enter the order of the matrix:"); scanf("%d",
&n);
/* get the entries for the input matrix from the user */
printf("Enter your entries for the input matrix:\n"); for (i
= 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("The input matrix is:\n"); for (i = 0; i < n; i++) {
printf("\n");
for (j = 0; j < n; j++) {
printf("\t%d", matrix[i][j]);
}
5.9. EXERCISE
1) What is an array? Explain the features of an array and their uses.
2) In what ways does an array differ from an ordinary variable? What advantage is there in
defining an array size in terms of symbolic constant rather than a fixed integer constant?
3) Can an array be used as an argument to a function? If yes, explain with examples.
4) Explain the concept of multidimensional arrays in ‘C’ Language.
5) What do you understand by strings? How do you declare a string?
6) Write a program to copy one string into another. .
7) Explain the functions of the following:
i) StrcpyO
ii) Strlen()
iii) Strcat()
8) Can an array of pointers to string be used to collect strings from the keyboard? Justify your
answer.
9) How to find the end of the string?
10) What is the difference between three representations a, 'a' and "a"?
11) How do we read string including blank space?
12) Can we use scanf() to read string with blank spaces? If so how?
13) Declare two symbolic constants for the order of a matrix. Declare a matrix of that order.
Populate the matrix and display the same in the matrix form.
14) What will be the output of the following programs:
i) main()
{
int num[26], temp;
num[0] = 100;
num[25] = 200;
temp = num[25];
num[25] =
num[0]; num[0] =
temp;
printf("\n%d %d", num[0], num[25]);
}
ii) main()
{
int array[26], i; for(i=0; i<=25; i++)
{ . array[i] = 'A' + i;
printf("\n%d %c", arrayfi], array[i]);
},
iii) main()
{
int sub[50], i; for(i=0; i<=48; i++);
{
sub[i] = i;
printf("\n%d", sub[i]);
}
15) Write a function to multiply two arrays element-by-element, store the result in another array,
and return that array to the calling program. Do not pass individual elements.
16) Write a program to multiply any two 3x3 matrix.
17) Write a program to get a 2-digit number from the user and display it in words, e.g., if user
supplies ‘45’ then program should display ‘forty five’.
18) Write a program to transpose a matrix.
19) Write a program to read in an array of 10 integers and sort that array into ascending or
descending order depending upon the user s choice.
20) Write a function to receive an array containing real numbers, sum the numbers, and return the
sum to the calling program. Do not pass individual array elements.
21) Is 2-D array be the combination of 1-D array? If yes explain with the help of suitable example?
22) What do you understand by row-major implementation and column-major implementation of 2-
D array?
}
23) Write a program that reads a string from the keyboard and determines whether the string is a
palindrome or not. (A string is a palindrome if it can be read from left and right with the same
meaning. For example, Madam and Anna are palindrome strings. Ignore capitalisation).
24) Write a program which will read a text and count all occurrences of a particular word.