0% found this document useful (0 votes)
61 views31 pages

Array PDF

The document provides an overview of arrays in C, including their initialization, types (one-dimensional and two-dimensional), and how to manipulate them through various methods such as assignment and scanf statements. It explains the characteristics of arrays, how to print their elements, and the concept of multi-dimensional arrays. Additionally, it covers passing arrays to functions using call by value and call by reference techniques.

Uploaded by

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

Array PDF

The document provides an overview of arrays in C, including their initialization, types (one-dimensional and two-dimensional), and how to manipulate them through various methods such as assignment and scanf statements. It explains the characteristics of arrays, how to print their elements, and the concept of multi-dimensional arrays. Additionally, it covers passing arrays to functions using call by value and call by reference techniques.

Uploaded by

sgw058602
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Arrays in C ‘Syllabus : Initializing arrays, Initializing character arrays, Multidimensional arrays, Command line arguments. —| Se 3. 2-dimensional array elements are st0f€4 TOW by roy x ete. 5A. If multiple values are to be stored under the same Variable name, then arrays are used, In array single variable can be assigned with a number which acts as an index number or subscript. ‘The values are stored in the array in different memory locations indicated by the indices. These variables allow the, storage of ‘multiple values under same variable name. In other words an array is a set of sequentially indexed ‘elements having the same type of data. Each element of an array has a unique identifying index number. Changes made to one element of an array do not affect the other elements, Array can be used to represent vector, matrix, tables 1 What is an Array ? An aray is a group of similar type of dita elements stored in contiguous memory location, Each storage location in an aay is elled an anay clement. The data elements are addressed by conan, name, An array is declared by writing the data types, followed by the name, followed by the size (dimension) brackets. eg. int afl2) Arrays are also called as subsripted variables, Here the dimension means the numberof subscripts rain represent the elemens in aay, Remember the subscript of an aray must he positive integer number, as 2 Characteristics of Arrays ‘An array holds elements that have the same dg iF ata type, Array elements are sored in subseuen merry locations. subsequent memory location. Array name represents the address of the clement. Array size should be mentioned in the declaration Array size must be a constant expression and not 4 variable. staring 5.1.3 Types of Arrays ‘Arrays are divided in three types : 1. Single/one dimensional array 2. Two dimensional array Fig. S11 Syllabus Topic : Initializing arrays 5.2 _ Single / One Dimensional 52 Single/One Dimensional ‘The arrays that uses only one dimension to arrange iS ‘lements are called single/one dimensional arrays. A singlefone dimensional array can be used to rep 8 list of data items, which is also known as a v=" Single dimensional array uses single subscrift " Fepresent the element. A subscript is a numbet i! bracket followed after array variable name. SB: list [3], vector [10], a [12] ete. All the values of array are stored in memory ¥# ‘ either in a Tow or column, Every element oe ee Can be retrieved by indicating its location numb Index of the memory. © Scanned with OKEN Scanner ~The element indices cama chien first array ___ Clement is a(0}, second array element is a1} and s0 on. Afler ‘declaration ‘of ‘array, the data for the array Variables can be entered in the memory “the following methods. eee. 4) Arithmetic (assignment) statement b) scanf statement ©) By initializing « 4) Arithmetic (assignment) statement "= The value of the array variable can be supplied in the memory by use of arithmetic statement (i.e. assignment) a(0] = 1.22; a(t] =4.51; af2]=6.52; = In this case the memory is filled by using arithmetic statement. The above statements are the ‘The values for an array can be entered by using scanf statement. In this case the values in array ccan be entered by including the Scanf statement in for loop. Here the loop variable acts as an index. eg. in following example i will work as an index. In the above statement ‘i’ value starts from 0 and ends at 4. It reads 5 values of 'a' variable. These five data values can be supplied for ex. 3.14, 5.11, 2.43, 5.11, 6.23. They are filled in the ‘memory as values of arrays. ©) By initializing ar — The array can be given values directly at the time of its declaration as below. 4 int x[5] = (3, 5, -3, 1,4); = Im this case, the values for array elements are ‘supplied at the point of declaration and these 5 values will be assigned as; x0] =3, xi1] = 5,x(2]=—3. x13] = 1. xll=4 CG scanned with OKEN Scanner Dr. BATU) ") Printing array variables ‘The values of array variables ean be printed on Seren by using print? statement in the for loop, Here the loop variable acts as an index, eg. in following case, Following are the methods of printing the values 1) fa (nO, ie i) t Print *x{%d] = d\n", i, XL); ) In this method the valves of x{0] to x(4) will be Printed as : x()=3 xt=s xQ)= 3 xBl=1 x= 4 Ai) for(i=0; ie=ds 44), { Printf(sed\e", x{i)); ) In this case the value of x{0] to x[4) will be Printed in one row as : Se aad wdc 5.3 Two - Dimensional Arrays a ceional Araya A two dimensional array can be used to represent a table of data items consisting of rows and columns and is also known as a matrix, ‘The matrix in mathematics is a two dimensional aay Which uses two dimensions viz, row and column, The clement of the two dimensional aray is indicated by the row and column number in which itis located, The element of matrix is written as aij, where i stands for row and j stands for column number, [Syntax : datatype variable_name (row size] [column size x in aBlGh int b(4I[5}; int © (6}(8}; float x [10}{10}; floaty {20]{20}; ‘The structures like determinants, represented using these arrays, Remember, the capacity of «two dimensional array to Store the number of ‘lemens is calculated” by multiplying its dimensions i. an array e(6l(8) co, store 6 x 8 = 48 elements. ‘The declaration int a [3](3] can be assumed to create a structure as follows in the memory. ‘a’ naine of matrix Matrix can be 53 = The element 12 can be indicated by using the subscripts 22 i, af2](2] 12 = Where {2}(2] is indicating 3rd row and 3rd column of the matrix whose value is 12, 1) Entering values into an array ‘The value can be assigned to two dimensional array «elements in the same way as in case of one-dimensional array. 4) Arithmetic (assignment) statement ii) scanf statement iii) By initializing 4) Arithmetic (assignment) statement ‘The clement of array can be supplied a value by using arithmetic statement and by specifying the row number and column number. aloo) = 8 a(t2) = = 4 ! ») _scanf statement The value can be entered to a two dimensional fray using scant statement in a nested for loop, Where the outer loop generates the row numbes | and inner loop generates the column number, For(inO;i Myprogram Filel File2 d _ Here, on the command line Myprogram represents vee of our C (executable) program. Filel and File2 tne the parameters we wish tO pass as an arguments to ur program. These arguments get into our program by passing them to the mainQ function using special dummy arguments. In Bh wwe can specify two arguments which will do these things as; void main(int arge, char * argv); int arge : This parameter (argument count) counts the number of arguments passed from the command line. 2. char *argv[]: This is an array of pointers to characters (strings) which holds the — starting address of the arguments passed from the command line. Example Write a program that copies the contents of one file inio another. It should accept the arguments from the command line # include # include void main(int argc, char *argy[]) a FILE *fs,*ft; char ch; ‘f(argc!=3) { printf("Invatid number of argument _ eit): ts ® im array is a pointer. © scanned with OKEN Scanner asic Computer Programming (Dr. BaTY) Fefonen(aravle | if(PeeeNULL) "w"); printf("Eror in target file\n"); _ felose(fs); i: exit(); as while((chagetc(fs))!£0F) a } printf("File copied successfully\n"); _ felose(fs); felose ft); pute(ch, ft); } Assume that the name of this program is Mycopy.c. To rn this program make an .exe file of this program eg [Link]. Run this file from the command prompt ‘and specify the arguments there itself just like other system commands. eg. cil> Mycopy [Link] Newdatatxt = Itwill show the message "File copied successfully’. To verify, you can open the file [Link] and check whether the contents of [Link] has been copied into it. 5.7__ Strings (Character Array) Like arrays of integer, float we can have an array of characters. A sequence of characters is called string. The string is a character array stored in contiguous memory locations. The strings are used for ‘manipulating text such as words and sentences. — C does not support string as a data type. However, it allows to represent strings as character arrays. = The string is a one dimensional array of characters terminated with a null character (\0)) which indicates, the end of the string. — Therefore, the size of character array should be equal to the maximum number of character in the string plus ‘one, Each character needs one byte of memory space. ‘Syntax; char string_namel size Ex char name[20); ‘char str (10}; ‘char word| 40]; char line{80}; 58 Arrays in Syllabus Topic : Initializing Character pa Array 5.7.4 Initializing Character Arrays (Strings) A char type variable can hold only single character. Hence to store a sting we need an array because string is a sequences of characters. For ex. name, address, month, city are example of strings. C handles this type of information using an array of characters ~ _ Itis collection of characters (array of characters). In C, string has dual advantage that it can be accessed as a string and also as an array when required. ~The character array can be intialized in following two ways ; ‘char mycity (6] = "LATUR": ~ Inthis form the null character '0' is not necessary. The compiler automatically inserts the null character at the end. char city(6} = (LA‘,T,U,R,10}; ~The length of string LATUR is 5: and one: space is provided for null character (\0!). = The declaration of char city(6) needs 6 bytes under the array city(]. The null character, 0° will: be: placed automaticaly to represent end of array city{) when the enter key is pressed. a A cat eee String representation in memory ‘The common operations performed on character strings are : = Reading and writing strings. ‘Combining strings together. — Copying one string to another. — Comparing strings for equality. — Extracting a portion ofa string. Reading string — The input function scanf can be used with %s format specifier to read in a string of characters. char namie(20]: scanf("%s",name); — With this scanf statement, it terminates its input on first white space it finds ie, blank space, tabs, carriage returns, form feeds etc. For ex. if the name is "Shrikant Tandle', the scanf statement will read only Shrikant in array address, since blank space “after the °name “Shrikant" will terminate the string. = In case of character arrays, the ampersand (&) is not required before the variable name because the namie of fan array itself is a pointer, the base address of the string, Using scanf statement the length of the string should not exceed the dittensions of the character array. © Scanned with OKEN Scanner ring ‘The output function Printf can be used with %s format Specifier to print strings of characters, The format %s can be ‘used to display an array of character that is terminated by ‘ull character. Print” #s *, mame); ean be used to display the entre Contents of the aray name, c Computer Programming (Dr. BATU) £3 Writing Output world from put Now let's see the exact difference between scang tas oa Fe difrce boven sn 4 ts tn gg lio: ang ‘Table 5.7.1 Example rs ‘void maing) Sn seant ets No. se char name(18},city[15],post{15]; 1._| Itnceds %s. It does not need %s, Printf("\nEnter Employee data\n"); 2, [it ean read as many | It can read only one Scanf("*%stes%s" name, city, post); strings we wish string ata time, Printf("Name = %s City = %s Post = %s\n", 3, | Itcannotread a string | It can read a ame, city, post); with a blank space. | with or without blan- ap space. 5.7.2 String Input & Output Function ‘The difference between printf and puts function isa follows : ‘The input statement scanf and output statement printt function can handle basic formatted data types. There are irmesiaiea {wo special functions used to read and print the string. : 3 Sr rintt ‘puts 1. gets() function Ne gy 4 ‘The gets function reads a line from the standard input Stream stdin and stores it in memory. The line consists of all characters up to end including the first newline character Cw), gets then replaces the newline character with a null character (‘\0") before returning the line. This function reads the input with or without blank space. Example ‘void main() i char tine[so}; Printf("Input a strin sgets(line); printf("The line entered was:%s\n" line); } Output 4. | It can print as many | It can print only om! strings we wish string at atime, 5._| Teneed %s, Itdoes not need %s. © | Wecan add message. | We cannot aif ie messages, While dealing with the string the best ‘combination is efor reading and print fr printing, Example void main() char str[20}; gets(str); Printf("*%s\n" str); nut a string: Hello World | The tine entered was: Hello World! 2. puts() function The puts function writes string to the standard output stream stdout, replacing the string’s. terminating null character ("0") with a newline character (“\n) inthe output stream. void main() ihenke _puts("*Hello world from puts!" ); a 5.73 String Manipulating Functions ite C library. supports a large number of site handling functions that can be used te carry out many of the string Manipulations. The C program that contains H Statements of manipulation of strings, the header fl Giringsh> must be included in the program. Following #* ‘he most commonly used string handling functions: Function strlen() strupr() Use Converts string to uppercase © Scanned with OKEN Scanner asi je Computer Programming (Dr. BATU) This character. 40 Arrays in’ Function Output iw) | Converts a string to lowercase LONERE | snovt)__| Reverses string | surevi/__—____*____________| | 3. striwr(): convert string to lower case sepy)_| Copies a string into another to lower case. ‘Copies “a chatacters Of Ti ‘This function converts the given string into lower case- 07 ee TS of one string into | | {fits already in the lower case it remains as itis Taeai() | Append one sting atte end ofanomher | ___symae stb )s_—_—_———— ay smneat() | APPend n characters of one string atthe | | | YOld main() cend of another { emp) _| Compares two strings char word[20]="BATULonere"; x memp()_| Compares first characters of two strings strlwr(word): acmpi() | Compares wo stings by Tenorag whe | || printf(s\n" word); case } mempi() | Compares first n characters of two stings aera a>: | by ignoring the'case Output i batulonere z function gives length of string excluding the null syntax : strlen(str); at 4, strrev (): reversing a string the same place. is function reverses the given string and stores it at void main() syntax :strrevstr) { void main() char addr[10]="BATU'; { int n: char word[10]="INDIA"; _ nestrlen(addr); strrev(word); printf('The length=%bd\n"n); printf("%s\n", word); } — | |e Output Output The length=4 [Aton = Remanber we an wate car oa sion | 5 grepy d+ ting copy nt to each one ofthe library function. equivalent to each one of een ‘This function copies the contents of one string variable = We can write user defined function mystnt ) | ini oiner string variable, which will work exactly like the library function syntax : strepy(t,s); stren() nn void main 2, strupr () : convert string to UPPER case ; 0) ‘This function converts the given string i to upper case, Ifthe string is already in the upper case it remains as itis, ‘char s{10] = "Pune"; static char t[10]; strepy(t.s); printf("ss\n",t); © Scanned with OKEN Scanner BEF cane congue regen 0. BATU) 6. ‘strnepy () + Copying n characters into at's fimetion copies characters of one string variable ito other string variable, syntax : strnepy(s,n); Void main(), \ char s[20] = "DBATULonere"; static char t[20]; strnepy(t,s,5); rintf(*%s\n",); i Le Output DBATU 7. _streat() : string concatenation ‘This function adds the comtents of one string variable at the end of the other string, syntax : streat(ts); void main() char s{10]="Bombay"; char t{20]="New"; | __streat(t.s); * printf("%es\n",t); } Output NewBombay 8. strncatt() : concatenating first n characters This function appends first n characters of on variable at the end of the other string, syntax : strncat(t,s.n); string | void main() ae | char s[10}="Bomba | char t[20]="New"; strncat(t,s,3); rintf("9s\n".t); J i Output NewBom Arrays ing If strings are not matching then it gives the AScy, difference between first (WO un-matching character. = If difference is positive first string is greater thay second. If difference is negative first string ig sinaller than second lexically but provided tha, they are in the same case. be"; stremp(s) will give 0, be"; "abe"; stremp(s) will give -1 i, ASCII diff. between a and 097-98. ifs] = "bbe"; tII-"abe"s stremp(s,t) will give 1 i.e. ASCII diff. between b and a 6.98.97, ifsl] = "abed"; t(}="abe"; stremp(s,) will give 100 ie. ASCII diff. between d and Wie. 100-0. ifsl] = "abe"; t{]="abed"; stremip(s,t) will give -100 i.e. ASCII diff. between \p and di.e.0-100. ifs{] = "abe"; t{]="ABC"; stremp(s,t) will give 32 i.e. ASCII diff. between a and Aie.97-65, void main() L char s[10]="Hello"; char t{10]="Hello"; int n; n= stremp(s,t); if (n—=0) printf("Matching\n"); else Printf(*Not matching\n"); stmemp ( ) characters) + string comparison (first 9 This function compares first n characters of ont string with other. 9. stomp () : string comparison = This function compares two strings character by character. Ifthe strings are matching it gives zero, © scanned with OKEN Scanner asic Computer Programming (Dr. BATU) 7 t[10]="Weldone”; int 3 stmemp(s.t,3); if (n==0) printf("Matching\n"); printf("Not matching\n"); 41, strempi () : string comparison by ignoring case This function compares two strings by ignoring their ‘ease. It gives zero if they contain the same characters imespective of their case. Syntax : strempi(ts); void main() { char s[20]=" programming"; char t[20]="PROGRAMMING; int n; n= strempi(s,t); if (n==0) printf("Matching\n"): else printf(*Not matching\n"); 42. strnempi ( ) : string comparison (first in characters) by ignoring case) This function compares first n characters of one string with other by ignoring case. It gives zero if they are matching otherwise it retums the ASCII difference between first two un- 5:12 } printf(*Matching\n");, else printf('[Link]\n" Output Matching z 5.7.4 String, Pointer and Function array of character. InC the strings are represented as an lcit pointer which ‘The name of an array itself is an impli point towards the base address of an array. lence whenever we handle a string we use the name of ‘an aray ie. an implicit pointer. Every library function takes the string pointer as an input and manipulates the string, Hence using an explicit pointer with a string doesn't require any extra arrangement. Example void main( ) { char str{20] = "Hello world"; Ce char * pi © pest fA p= ent “l= printf (" s\n", p)r is Output Hello world = This concept is very useful and efficient in passing the strings to function. For passing a string to the function ‘we need to pass i's base address only = In the function either we can use a char, pointer or a dummy array of char, Example void main( ) void show (char); /* show (char); *7 char str[10] = "Welcome"; show(str); © Scanned with OKEN Scanner Ar sin Basie C: ing (Or. BATU) 5 ic Computer Programming ( pian) 5.8 Solved Examples Program 5.8.1 iftatil>large) Write a program that finds the average of 10 numbers using largeeali]; an array. } eee Soln.: printf(*Largest=%d\" large); oe # include _——————EE_ void mait TE ear Program 5.8.3 { read and array and reverse all its {nt a[t0}; Write a program to BEC sun ‘elements and display. float avg; a Te printf("ENTER 10 NUMBERS\n"); include © Scanned with OKEN Scanner za asic Computer Programming (Or. BATU) is 14 arrays in C it(alil>large) ee ae a number to find in the large-afi; oe fretiemall) Scanf("%ed", number; ala ee i const int MAX_SIZE = 100; void main() { int a[MAX_ SIZE]; inti, n; printf("Enter how many numbers\? Max.100\n"): scanf("%ed", &1n); printf("Enter Yd numbers\n", n); forli=0;i for (jnit1: je void main() { : { if (alil >ali) ‘int a[10]; { ‘inti, flag-0; temp = ali]; ~ int number, position; ali] = ali; printf(*Enter alist of 10 numbers\n"); Sie temp: _Forlinditerarirs) ot Ea | gina | sea anf("%ed", Salil); aa) | eed printf("The number %ed is found in the list 3& aud position\n", number, position); else printf("The number %d is not found in the list\n", number); he, Program 5.8.7 rte a program to search a number in a given list using binary search. If found, give its. position. Soin. Pincuude void main() { ‘int a[10];, int start, end, mid ,flag=0; ‘nt number, position; int i, j, temp; printf ("Enter a list of 10 numbers\n"); For(ieO;ic=9;i+4) scanf("*hd" Bali); for (iH0; i<-8; 14+) _/* sort array in ascending order*/ © Scanned with OKEN Scanner Printf("Enter a number to find in the Uist\n"); Scanf("ed", &number); i start = 0; end = 9; while (starteend) mid = (starttend) /2; if (number==afmid] flag=1; position = mid break; } ‘if (number void main() { ‘nt a[10]; int i, count=0; ‘int number; printf(’Enter a list of 10 numbers\n"); *For(ie0;ic=9;i++) : scanf("%d", &ali]); printf("Enter a number to locate in the list\n"); scanf("%bd", &number); for(in0;i<=9;i++) Program 5.8.9 \Write a program that reads twenty five numbers and find out how many of them are even and how many are odd rumbers. Soln. { if(number==a(i]) { count=count+4; } I ‘if(count>0) printf("The number fas occurred for %d times\n", count); else i printf("The number is not found in the list\n");, } W include void main() { ‘nt num[25],i, even=0,0dd=0; printf(“Enter 25 elements of array"); for(i=0;icn24;i++) ie scanf("%ed", &numfi]); es b oe > ‘f(numfi}%2==0) evens; else odd++; t printf("\nEven numbers = %bd", even); printf("\nOdd numbers = Yd", odd); Program Write @ program to read a list of 25 numbers and find out how many of them are positve, how many are negative and how many are zeroes. Solr # include void main() int num[25], i, neg=0,pose0,zero=0; printf("Enter 25 elements of array"); for(inQrien2aiitt) i © Scanned with OKEN Scanner (FE easic Computer Programming (Dr. BATU) 5:16 Arrays in © Ran ee Saurnlil)A For(ic0st<57-4) for(inOjicn24;i++) scanf("%d" &ali]); { for(in0;i<5;it+) ‘if(numfi]>0) scanf("%d", &b[i]); poste; tet ‘if (numfi]<0) ee neg++; segbes if(num{i}=0) ae iy ‘Zero; if(aliJ—bi)) 3 clks+]eali]: printf(*\nPositive elements =%4d! pos); : t printf("\nNegative elements =%d"neq); : a ‘neg); ae ements in these pie proes — Salvi, } ei ‘The common elements in 28 EGE GS for(inO;ickiit+) Program 5.8.11 Pantie eae D)2 Wite @ program to read two arrays and merge them to form ee a thi array. nes Sol Program 5.8.13 Hinclude alil-temp: Void main() p ji } sid eS } fee mbaTS) [Link]): } ee © Scanned with OKEN Scanner Mf("List is ascending order\n"); for (iH0; ino; a4) Printf("%d\n",afi)); Arrays in Basle Computer Programming (Or. BATU 7 ee Note: In the above program it we change the condition (alil>ali} ) to ( afi}eaij] ) then the above program for(im0i ) scanf("*bd", Bali): For(ind;iali+1]) Hi temp=al j J; af j nal j +1]; al j +1]-temp; } } } printf("List is ascending order\n"); for (i-0; i<+9; i++) printf("%d\n",a[i]); } Program 5.8.15 Write a program that finds the sum of all array elements. it a[10], i,j, sum=0; aa Soin: # include # include void main() void main() { int af10]; ini printf(“ENTER 10 NUMBERS\n"); For(in0;i<=9;i++) scanf("%ed" Bali); For(i=0;i<=9;i++) afi] = afi) * afi]; printf(“Array elements are\n"); for(i=0;ic=9;it+) printf(“%ed\n" afi); } Program 5.8.17 Write program to copy elements of one array into another array. void main() { int a[10}, b[10]; ini: printf("ENTER 10 NUMBERS\n"); for(i=0;i<=9;i++) scanf( "ed" Bali); Forlin0;i void main() : int a[10], b{20); ini printf("ENTER 10 NUMBERS\n"); for(ieO;i<=9;i+4) scanf("ed" Bali); for(i=0;i<=9;i++) bli] = af 9-1}; printf("Elements of second array becomes\n"); For(im0;i void main( ) { int a[10],i=0,n; printf(“Enter 10 elements greater than 30 conly\n"); while(ic=9) “i scanf("%d”,8n); if(n>30) { afi] =n; i; } } printf(“Array elements are\n"); for(i=0;i<=9;i++) printf(“sed\n",ali)); i Program 5.8.20 ; Write a program to display addresses of each array index. Soin, : avraysin © int a(t0} 4; for(inO;lemOiie+) printf(“Address of index %ed is You\n"); a Examp! using 2-D Arrays Program 5.8.21 Write a program to read and print a matrix of 8x 3. Soin: include void main() { int a(3](3]; for(j=0;)<-2;j++) { scanf("%d" a[i1L); for(j=O;j<=2;j++) { printf("%d\n",ali} il): } } Program 5.8.22 Read a matrix of 4 rows and § columns and display it in a ‘matrix form. Soln.: # include void main() { int a[41{5]; int ij: forlimO;i<=3zit+) { for(j=0;}=4;5++) { scanf("%ed", Bali} (il): # include + void main( ) © Scanned with OKEN Scanner FOr(jmOjjemdijt+) ‘ printf(*%d\t" ali) UiD)> printh\ns } Program 5.8.23 Read a matrix of 3 rows and 3 columns and display whether itis a null matrix or not Soin: NUN’, all eltmenss are lude void main() int a[3][3); int ij flag: for(i=0;ic=2;i++) { for(j=O;j<=2;j++) { scanf("*od" 8afi] [j]); } For(ieO;ice2;is+) if(ali)Gl!=0) { flag-0; break } } L if(flage=t) printf("It is Null matrix\n"); else printf("It is not Null matrix\n"); } Ralabenaa ccc So ee include void main() { int a[3)[3]; int ij; ‘ for(inOsim=) maxeali)U): } } printf(*Largest element=%4\n", max); 3 # include void main() { int a(4](4): int rowmax(4]i ints, j, largest for (ie Oric=3zi++) { for(j=0;j=<=3i++) scanf("%d" Sali) iD): } forlindsicn3iit+) rowmaxtil-ali}[0}: for(§=O:i<-3ii++) if(ali]}>rowmaxtil) rowmax(i]=-alil Lil } largest-rowmax0]; forlietii<=3;i++) ‘f(rowmaxfil>laraest) largest=rovimaxi]; } forlieO;i<=3zi++) { printf("Largest element from %d rowed \n",t+1,rowmaxlil); } printf("The largest number=%d\n" largest): 3 Program 5.8.28 Write a program that finds the sum of numbers from each row of 4 x 4 matrix. Also find the total sum of the elements in matrix Soin. : PON SEM sca sceTea # include Program 5.8.27 Wite a program that finds the largest number from each || vaid main() of a4x-4 matrix. a ‘Also find the largest number among all the elements of | | matrix “int af4][4); © Scanned with OKEN Scanner EEF asic computer totalsum=totalsumsati[j]; } for(i { printf("The sum of element from %d row = %od\n" +1, rowsum[i]); } printf("The total sum=%d\n",totalsum); in i4+) } Program 5.8.29 Write @ program that reads a matrix of $x3 and find out the largest element from each row and store itn the 4th column. Soin. : # include void main() { int af3)[3]; int transpose[3][3]; / ] int a[3]{4]; for(ie0;ice2;i++) int ij; { for(i-O;i void main() £ int a[3][3]-b(31(3}-c131131: inti, jz printf("ENTER THE ELEMENTS FOR 1st MATRIX\D"); for(inO;i<=2si++) { for(jmOri—=2:it+) scanf("%bd", Bali]Li]); } i; printf("ENTER THE ELEMENTS FOR 2nd MATRIX\n"); For(ieO;i void main() { static int [3113], 01311311313): int ik: printf(ENTER THE ELEMENTS FOR 4st MATRIX\n"); for(ieO;i<-2ii++) For(ja0;j<=2;)++) scanf("%d",8ali]Li]): i } printf(” ENTER THE ELEMENTS FOR 2nd MATRIX\n"); for(inOri library function. void mystrlwr(char *); Soin. void main() # include { int mystrlen(char *); char word[10]="LATUR"; void main) ‘mystriwr(word); mt printf("%s\n" word); char univ{J="DbatuLonere"; } int len; void mystriwr(char * nemystrlen(univ); ee eo) : printf(*The length=%d\n",len); | while(*pieoy ‘int mystrlen(char * i oe a) ‘f(*p>=65 88 *p<-90) int n=O; *p="p+32; while(*p!="\0') pH { } ney } i a : Be |-Program 5.8.96 reun Wie @ pregram to reverse a sting without using lira i Soin, : Program 5.8.34 # include ‘Write a program to convert a string into upper case without void mystrrev(char [ }); using library function. void main() © Scanned with OKEN Scanner - & ‘Arrays in { char word[10}="INDIA"; Goins mnystrrev(word); # include printf("4es\n", word); void mystreat(char*, char *) } void main() ‘oid mystrrev(char p[]) { { char source[20]="University”; int nie char target{40]="Technological”; char temp; mystreat(target,source)? n= strlen(p); . printf("%es\n", target); for(i=0,j=n-1;i<=(n-1)/2;i04,j--) } { void mystreat(char *t,char *s) temp=p[i]; { Z plil=plil: while (*t!=\0') ‘/*go to the end of pLi}=temp; target*/ } { i tee Program 5.8.37 } ‘ Wite a. program to copy one sting into another sting while (s'<\0).._/tadd source at the variable without using library function. end of target */ Soln. : { # include a void mystrcopy(char *, char *); si te void main() + { wt; char source[10]= "Technology"; } char target[10]; program 5.8.38 ystrcopy(target,source); Wie a program to compare two strings without using library printf("%es\n" target); function. Boles sa ee void mycopy(char *t, char *s) Tae ‘void mystremp(char *, char *); while(*s!=\0’) id aint) 4 { sere char source[80]; sii char target[80]; a i int n; y gets(source); ae sets( target): Pe eio a ee ee | lean aes “i Program 5.8.38 ‘f(n=0) Write a program to concat (add the contents of one string at i printf("The strings are matching\n"); e the end of another) two strings without using library function, © Scanned with OKEN Scanner BE ssi comput ogaran Witte a program that counts all the blank spaces in the given sting. Soin, : # include # include void main() { char word[80]; int i, n, count = 0; | gets(word); nestrlen(word); for(iaQ;icen-1:it+) { ‘f(wordfi]—~’) count++; i printf("[Link] blank spaces in a given string = ‘ed\n", count); e: UE nde | Program 5.8.61 Write @ program that finds the occurrence of the given character in the given string Soin, #include # include void main() Sol Write @ program that counts all the vowels from the given string.(A, E, 1,0, U) ‘arrays in © a { a | a brintf(*The strings are not matching \n"): char word 80): pocmtecureememe ||| is nen ve lunmatching charsted\n",n); Me nes eto } gets(word); i Void mystremp(char *t,char * printf("Enter a charcter\n"); { eae) scani("%0c" 8x); viile(*t\0]}¢1-\0) nestrlen(word); i for(ie0; tean-t; i++) if(tti=*s) i retum(*t-"s); if(word[i]=x) ee count ++; } d for printf("The character %bc has occurres return(0); ‘ted times\n", x, count); d Program 5.8.40 Program 5.8.42 { } # include # include void main() word{i}-~€'|word{i}==T] word[i]~0'| word[iJ=='U') count + +: d\n", count); char word[80]; int, n, count = 0; gets (word); strupr (word); nestrlen(word); for(in0; fen-1; 144) iu if(word{i} A} 3 Drintf("No. of vowels in a given string = Program 5.8.43 Write a program to check whether given sting is @ palindrome or not. Palindrome is a string which when we ‘ead from let or right it is same. e.g. nitin, malayalam, level, abba etc. © Scanned with OKEN Scanner Pepe ss pny Sih z Arrays in C Sol Br Lerten] Finclude void main( ) # include { void main() char word(80); { int ijn; char word [80]; gets(word); inti, nj, flag 4; n= strlen(word); aets(word): for(inQ;ican-1;i++) nestrlen(word); { Feat . (i=0,jen-1'=(n-1)/2;i44,j--) : f(word[i}=="’) if (word[i] !=wordfj]), Vee e fae. word[iJ-wordli+a]; break; ae if (word[i}—=" o y if (flag—=1) } t printf("It is a palindrome\n"); printf(%4s\n?,word)s else } : printf(*Tt is not a palindrome"); se Wie I | Wt program that encrypts and decrypts a string. (encrypt EAS Fie Gave pon cane Gore wang TERT] | rv0nns encodes and decrypta means decodes) follows. Soin. : F include P include # include # include void main() void main() { v char word [80]; char word [80]; char temp [80]; int in; gets(word); gets(word); strepy(temp,word): n= strlen(word); strrev(temp); For(inO;ieen-4;i++) if(stremp(word,temp)==0) { printf("It is a palindrome\n"); word[i}=-word{i]; else } printf("Tt is not a palindrome"); printf("The string after encryption:%s\n",word); } for(ieO;iean;i++) ‘ Program 5.8.44 i oh Wie a program to remove all he bank spaces fom [Link] | | 4 wordli}—word[i]; sting lagi Sr Soin. : __printf(The string after decryption: %s\n",word): [ # include : - include es © Scanned with OKEN Scanner ‘arrays in CF basic computer Programming (Or. BATU) 527 rr Program 5.8.46 Write a program that reads a string of digits (max. 32 bits) in, binary and converts it into decimal Sol # include #include fincludeemath,h> void main( ) Ht char number{32]; int ilen,p; long unsigned decimal; printf("Enter a number in binary\n"): scanf(%s" number); len = strlen(number); decimal-o; p=len-1; For(imO;iclen;ir+) { ‘if(number[i} ') decimaledecimalepow(2,p); Pep-l; } printf("The decimal equivalent of %s = %lu\n" number, decimal); } Program 5.8.47 Write a program that reads a string of digits in octal and ‘converts it into decimal. Soin.: # include 4# include #include void main() { char number[20}; inti, len, p; long unsigned decimal; printf(“Enter a number in octal\n); > scanf("%es", number); for(i0;iclen;i++) switch(number[i]) { ‘case '0': decimal = decimal+0*pow(8,P); break; decimal = decimal+1*pow(8,p); break; 4 case '2': decimal = decimal+2*pow(8,p); break; case '3'; decimal = decimal+3*pow(8,p); break; case" case '4'; decimal = decimal+4*pow(8,p); break; case '5'; decimal = decimal+5*pow(8,P); break; fecimal = decimal+6*pow(8,p); break; jecimal = decimal+7*pow(8,p); break; } P=p-1: } printf(“The decimal equivalent of %s =Mlu\n", number, decimal); } PA tent Seen EUS Q.1 How to declare two dimensional array? ‘Ans. : To declare a two dimensional array, we have to provide numbers of rows and numbers of columns, To declare two dimensional array, general syntax is: data-type name{row_size][column_size]; Q.2 Is it possible to declare a variable eae sized array? Ans. : No, its not possible to declare a variable sized array. While declaring an array, the size must be a positive: ‘nonzero-integer console number. For example, int af10}; Jhs possible But the following block of code is not possible, intn; ed es printf(“Enter array size :"); len = strlen(number); ; p te scanf(“%d”,&n); decimale0; | a Se int ala}; variable sized array is not allowed to declare ee 4 © Scanned with OKEN Scanner ic Computer Programming (Dr. BATU 28 ee = Gan we store negative values in an arr OF asi Ttis declared a . 7 datatype name { n0.]; Igsteuves) we cat store negative or positive values in an ex. ay ist ti its datatype). Ifthe data array (pase om HS lata-type of an array is armed then we can store ony positive values and it the umeype of a aray 18 signed then we can store negative ‘nd positive walle Q-4 Can we pass an entire atray to another fanction as argument? Justify + Yes, we can pass an array to another function as nt. This can be done by using the concept of call by aMjue or call by reference, In the call by value we pass ‘Waves of array elements to the function, whereas in the call py reference we pass address of array clement to the function Q.5 Is it necessary to pass the size of array as parameter, along with an array? ‘ans. : Yes, itis also necessary to pass the total number of ements in the array, otherwise the called function would not know when to terminate the loop. Q.6 Justify the [Link] main(int * argv D) ‘ana: Above statement is used for command line argument, fat arge : This parameter (argument count) counts (he umber of arguments passed from the command line, Thar eargyt ]: This is an aay of pointers to chamee® (Grings) which holds the starting adress ofthe arguments ‘passed from the command line 7 What. is the differens puts( ) functions, ‘ans. : The gets function read Ans. arge, char ce between gets(,) and a line from the standard input avn stain and. stores it ia memory. THe Poe function sete string othe standard output seam stdout replacing the sting’: terminating null character (X0”) ‘with a newline ‘character (\n’) in the ouput stream. Q.8 Define array and give its types ‘ane. An array isa group of similar type of data clement ae in contiguous memory locations. Ibis aso defined as the collection of the data items of the same {YPE: ‘The data ‘elements are addressed by common name. ‘Arrays are divided in three tyPes 2) Single / One dimensional arrays ©-B, 6 (10)) 1b) Two dimensional arays (ee: x (414) ©) Malkiimensional arays (e 2 (210518) Q.9 How do we declare one dimensional array ? ‘Also show how to initialize it? Ane. :'The arrays that uses only one dimension to aratge its Genents. are called -single/one:! dimensional ar) A Singleone dimensional array can be wed represent a list ‘of data items, which is also known a5 @ Vector float vector (301; Itis initialized as follows; int x(5)= (3554-3 1041 which means x(0) = 3, x11) xid)=4 @. 10 How do we can print the elements of a twor dimensional array ? JJements of two dimension it and nested for ‘numbers and inner 5 x(2 = 3, 3) = 1 Ans. using printf) statemen oop generates the row column number. for(je0;i<-2i++) pvietend\ tall GN); Q.11 What is What is its use? to program may represent a file ‘Command line is a line from to operating system orto different programs. Ex, Cb Myprogram Filel File2 Here, on the command line Myprogram represents the name the program, ‘which we pass the arguments name of out C (executable) program. Filel and File? are the parameters we wish o pass as an arguments to Out ProBFam Tt is useful to pass the input to the program in a faster and simple way. By using this, C programs can be used like ‘operating system commands, Q. 12 Explain about the arguments arge and argv. Ans. ‘In main() we can specify two arguments as follows; ‘void main(int arge, char * argv{ J) where; 1. int arge : This parameter (argument count )eounts the ‘number of arguments passed from the command line. 2, char *argv{J- This is an array of pointers to characters (etrings) which holds the starting address of the arguments passed from the command line. @.18 How do we initialize a character array ? ‘Ans. : The character array can be intialized in following two ways ; char mycity [6] = "LATUR": © Scanned with OKEN Scanner LF asic computor ramming (Or. BATU) 5.29 In this form the null character ‘ois not necessary. The Multiple Cho compiler automatically inserts the null character at the end, F data elements. char mycity(6] = (LAT UR AO; 1, An arrays act of date It is possible to specify every individual character (a) similar etal AA separately using single quote. (c) overloaded (@) virtu: Q.14 Explain in short about gets() function. 2. For an array, index number 2 refers to ‘Ans. : The gets function reads a line from the keyboard and element number - ; Stores it in memory. The line consists of all characters up to (@2 (3 @4 (d)-2 Ans.:(b) end including the first newline character (‘\n). gets then ‘ i replaces the newline character with a null character (\0') | 3. A'two dimensional array at gd ie Coca before returning the line. This function reads the input with ____ elements. 3 or without blank space. (a) 44 (b)8 (4 (d)16 Ans.: (d) sn Sime Hs aD 4: In ease of multi-dimensional array, the first een subseript specifies the ee Q.15 Give the difference between printf() and second subscript specifies the. ae puts(). and the third subscript, specifies the eet number. (a) row 2 (b) plane 1 Sr ee Priatty a ieee: (@) largest Ans. : (a), (b), (e) 1, | It can print as many | It can print only one Rigs waaiat peace Te uae elanlenttcsaialad 2._| Itneed %s. It does not need %s. be passed by just passing the name of the array. We can add message. _| We can not add messa z: ee a ei ees (@) last (b)n=1 (©) zero (A) centre 4,_| Bx. Printt Ex puls(oame); Ans. :(e) (Name =%s”, name); 6. Just passing the address of the zeroth element of the array to a called function is as ‘good as passing the entire array to the function, (a) True (b) False Ans. : (a) @.16 List out any four library functions with their meaning used to manipulate strings. i) strlen | Finds length ofa string my : supe | Convene ing sone ou ae aa ant iil) ster ners a string to lowercase iv) strev | Reverses string Ans. :(d) ay Ciena Hing tals oe 8. C supports string’as a built-in datatype. vi). streat ‘Append one. string at the end of (a) True (b) False Ans. :(b) another, 9. The format specifier used to read-write string vil) stromp | Compares wo strings | ie : Q.17 How can we use a pointer to a string? (a) Me“ () Hs (6) este (A) string Ans. : In C, strings are represented as an array of character Ans. : (b) ‘The name of an array itself is an implicit pointer which point | 10, ‘The towards the base address of an array, Hence whenever we handle a string we use the name of an array ie. an implicit e function Compares two strings by ignoring the case. aa (@) strempi() Hence using an explicit pointer with a string doesn't strom) require any extra arrangement, fo atrompi) It can be used as follows; (@) streomp_ignore_case( ) eK char str{20] = "Hello world’, 11. Every library function takes the string pointer char s z as an input and manipulates the string. pest ace eee @) True ©) False Ans. :(a) ‘We can use the pointer p in place satel © Scanned with OKEN Scanner 13. ue 15. 16. a. 18. 19. 20. Bip not a standard functio Paseaiaat)™* tay aaah (© streat( ) (@) distrset()” “Ans. : (a) Which header file should be i using standard string es Hpaigied for (a)streamh — (b) bastdioh (© cstdlibh (4) dstringh Ans.: (a) A three- dimensi At ional array can be thought of (a) array (b) array of arrays (©) array of arrays of arrays (@) None of these ‘Aris 110) Which of the following statement is correct about array? 1. array has sequential storage 2, array is collection of dissimilar data type 3, array is collection of similar and dissimilar data type (a) only 2 (b) only 1 (@) 1and2 (@)allofabove Ans. (b) Tfwe print ‘\0’, what will be the output ? (a) error (b) \\0 (©) \0 (@) blank Ans. : (d) dimension array is not possible. ase somes ore (70008 Aa) Was: £00) What is the maximum size of character array ? (a) NoLimit _ (b) 128 (©) 256 (@) 65535 Ans. :(@) Index of an array starts from. (@)0,(b)2. (©) 2 (d) depends on compiler “Arrays can be passed to a function bby passing its ‘Ans. : (a) (a) address (b) value (© both a and b (d) None Ans. : (©) _____fanetion convert the string in uppercase. (a) strlwrt) (b) strupr() (@ atrepy() (a) streatt) int pl3}={ 4, 4, 7}; P13/2I=p13-2); ence (a1 (b)4 (c) 0 (d) Error ‘Ans. : (b) ‘void main() ee { char a[5]=(0,8" printf(“%s",a)s (a)D (b) DBATU (©) garbage (d) error 24, What will be the output for the following code. The ‘Ans. : (b) ‘void main() { int afb ] = { 10,20,25,30,40}; ‘int * p= ar po3 printf("sed",*P); 2 (10 (b)20(e) 80 (@)40. Ans.z(©) 25. In, the boundary of an array is not checked by the compiler. (a) True (b) False Ans. : (a) 26, While initializing ‘two-dimensional array. which dimension is optional 2 (a) first (b) second (c) third (d) fourth ‘Ans. : (b) 27. What will be the output of following code. ‘oid main() ie ‘int n= 10; int an]; printf("*ed”, aft0)); L (@)10 ©) 0 © Garbage (@) Error Ans. : (d) 28, What will be the output of following code. a mae © Scanned with OKEN Scanner PEP acc computer ramming (Or. BATU) (a) TECHNOLOGICAL (b) TECHNOLOGICAL LOGICAL GICAL © Te (@ Brror Ans. : (b) 29. What will be the output of following code. void main() { ‘char si[3] = “ABC"; char s2[3] = “abc"; “printf("9d”, stremp(s2,s1) ); (@)abeABC ——(b) 0 (©) 82 (a) Garbage Ans, 30. What will be the output of following code. "void main() “int a[3] = {-1, 0,1}; a{-1] = a[0] + a[2]; ; printf("%%d", af-1]); (@)-1 )0 (© Garbage (@) Error Ans. : 31. What will be the output of following code. void main() jf int a[5] = {1, 2, 3, 4,5}; ‘int i, sum = 0; for (i=0; i<4; i++) sum += afi)*afi+1]; printf("%6d”, sum); 531 a4 as a6 as a4 } (a) 15 (b) 120 (c) 40 (a) Garbage ‘Ans. :(c) Review Questions Q.1 Whats an array ? What are its types. (Sections 5.1.1 and 5.1.3) Q.2 How do we can pass array elements toa function 2 (Geotion 5.5) Q.3 Explain the initialization of one dimensional and two ‘dimensional aray wth an example, (Gections 5.2.1 and 5.3(c)) Arrays in © What le a sting ? What is the advantage of topresenting the string using an array. (Beotion 5.7) Give the difference between a) scant and gets b) printf and puts. (Section 5.7.2) : How we can access the stings using pointers in function 7 (Section 5.7.4) Explain the diferent string library functions. (ection 5.7.3) Programs for Exercise Write @ program using one dimensional array to implement binary search. ‘An election is contested by 5 candidates. The candidates are numbered from 1 to 5 and voting is done by marking the candidate number on the ballot, paper. Write a program to read the ballots and ‘count the votes cast for each candidate using an array variables In case, a number read is outside the range 1 to 5 the ballot should be considered invalid. The program should count the invalid ballots and should declare the winner. It two two-dimensional arrays are given, sort them in ‘ascending order in the program. ‘Also make an arrangement to merge them into single sorted array. There Is a class of 50 students. Every student is having 5 subjects. Write a program that reads the ‘marks of § subjects of each student. Calculate the total marks obtained by each student. Find out the highest total obtained, ‘Write @ program that reads a matrix of m xn and Calculates its determinant value. Write the program that reads a name and prints the ASCII codes of every character inthe name. ‘Write the program which reads a text and counts all ‘occurrences of a particular word. ‘Write the program that extracts ‘and prints the extracted portion, Program should read the choice of the user. Write @ program that reads a string and counts ‘number of words in it @ portion of a string ‘Write @ program using function to read a string and feplace all its blank spaces with the character ‘+ Ex. It the input is. "| am an Engineer * then the Output should be "lsamsan+Engineer" ooo © Scanned with OKEN Scanner

You might also like