Successfully reported this slideshow.
Upcoming SlideShare
×

# Arrays and library functions

565 views

Published on

Published in: Education
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

### Arrays and library functions

1. 1. Page 1 of 13 Arrays and Library Functions Arrays: - An array is a collection of variables of the same type that are referenced by a common name. It consists of contiguous memory locations. Need for arrays:- For large applications or calculations say to find the average marks of 50 students if we use 50 different variables the job will be cumbersome and tedious and program maintenance will be very difficult. But if we use array the remembering and managing these variables will be easy. To make the program complex –free and more understandable array is used. Declaration of arrays: Syntax:- data-type array-name[size]; For ex:- int A[10]; float B[20]; char C[30]; where data-type refers to any fundamental(or primitive or in-built) data types, array-name will be any valid identifier name and size will be any number which indicates no. of elements the array contains. Types of Arrays:- Arrays are of two types:- (i) one-dimensional arrays and (ii) Two- dimensional arrays. Both the arrays can be of numeric as well as character (or string) types. (i) One-dimensional (or single dimensional or 1-D) arrays:- It is a collection of similar types of elements referenced by a common name. The elements of the are referred by their subscripts or indices. For eg. int A[5]; The above array will be having elements : A[0], A[1], A[2], A[4], A[5]. Array subscripts ( the numbers which are within [ ] ) always starts with number 0 not 1 in C++. Subscripts are the locations of the elements within the array. Memory representation of 1-D array Let us take the above example which is int A[5]; A[0] A[1] A[2] A[3] A[4] LocationStarting 25 -13 44 0 10address value Where A[0] is the first element, A[1] is the second element and so on. The last element (i.e. 10 here) always having location A[size-1]. Each element contains 2 bytes of memory. The address of first element of the array i.e. &A[0] is called the base address of the array. Note:- The name of the array (here A) is a pointer to its base address i.e. first element’s address (i.e. &A[0]). Size of the array in memory = data-type X size of the array For the above array the memory occupied will be 2 X 5 = 10 bytes. We can find it using C++ coding also cout << sizeof(A); here sizeof is a operator which is used to find the size of any data type, variable or derived data type in bytes and A is the array name. Initialization of One-dimensional array (Numeric type):- There are two types of initialization (i) Sized array initialization and (ii) unsized array initialization (i) Sized array initialization :- It can be done during the program writing (i.e. before program execution) or during the program execution (Using Loop). For ex:- int A[5] = {12, 13, 20, 5, 2}; Prepared By Sumit Kumar Gupta, PGT Computer Science
2. 2. Page 2 of 13 float B[4] = { 3.4, 4.5, 6.2, 7.8}; This is sometimes called direct initialization. code segment: int A[5]; for( int i=0; i<5; i++) cin >> A[i]; Here the values must be provided by the user during the execution of the program. In the first case the values are actually assigned during the compilation time and in the second case the values are assigned during the execution time by the user’s input. (i) Unsized array initialization :- It can only be done in following ways: int A[ ] = {2, 5, 17, 10, 12}; // No size is given within [ ] char str[ ] = “Kendriya Vidyalaya”; The compiler will automatically fixed the size of the array. Here the advantage is that the number of elements can be increased or decreased without considering the size. It is more flexible whenever there is a requirement of direct initialization or the values are known to the user. String as an array:- C++ does not string data types rather it implements string as one- dimensional character arrays. String is defined as a array of characters that is terminated by a null character ‘0’. For ex:- char str[20] = “Kendriya Vidyalaya”; It can be represented as Location in the arraystr[0] str[8] str[18] K e n d r i y a V i d y a l a y a 0 The above array contains 18 characters , but it can contain maximum of 19 characters i.e. size – 1 characters and one space is reserved for null character. Here the length of the array is 18. The position of null character is not taken for finding the length of the array. (i) Two-dimensional (2-D) arrays:- A two-dimensional array is a multi one-dimensional arrays. It consists of rows and columns i.e. it is in a matrix format. For instance an array A[m][n] is an m by n table with m rows and n columns containing m X n elements. The no. of elements = no. of rows X no. of columns One of the use of 2-D numeric array is matrix manipulation which is one of the important concept of mathematics. Declaration of 2-D array: The general form of a two-dimensional array is Syntax:- Data-type array-name [rows] [columns]; Where data-type is any base data type, array-name is any valid identifier name and rows, the first index indicates the no. of rows and columns the second index, indicates the no. of columns. For ex:- int Price [4] [5]; The array Price have 4 elements Price[0], Price[1],……., Price[3] which itself an int array with 5 elements. The individual elements of Price are referred to as Price[0][0], Price[0][1],……., Price[0][3], Price[1][0], Price[1][1] and so forth. The last element will be Price [3][4]. Memory Map Representation :- Ex:- int Price [4][5]; Prepared By Sumit Kumar Gupta, PGT Computer Science
3. 3. Page 3 of 13 Columns n-1 0 1 2 3 4 0 1 Rows m = rows, n = columns 2 3 Price [3][4] Price [1] [1] m-1 Size occupied by the above array in memory = data-type X rows X columns = 2 X 4 X 5 = 40 bytes C++ statement will be : cout << sizeof(Price); Array of Strings:- The two-dimensional character array is known as array of strings. The size of the first index (rows) is the number of strings and the size of the second index (columns) is the maximum length of each string. For ex:- char days [7][11]; Declares an array of 7 strings each of which can hold maximum of 10 valid characters where 1 extra to take care of the null character ‘0’; The above array of strings appears in memory as shown below: (11) 0 1 2 3 4 5 6 7 8 9 10 0 M O N D A Y 0 1 T U E S D A Y 0 2 W E D N E S D A Y 0(7) 3 T H U R S D A Y 0 4 F R I D A Y 0 5 S A T U R D A Y 0 6 S U N D A Y 0 Array Initialization:- Like One-dimensional array two-dimensional array can be initialized in two ways:- (i) Sized 2-D array initialization int SQ[3][2] = { 1, 1, 2, 4, 3, 9 }; int SQ[3][2] = {1,1, 2,4, 3,9}; Prepared By Sumit Kumar Gupta, PGT Computer Science
4. 4. Page 4 of 13 For Array of strings: Char Months[12][4] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”}; (i) Unsized 2-D array initialization int Cube[ ][2] = { 1, 1, -- rows should be left blank 2, 8, 3, 27, 4, 64 }; Char Months[ ][4] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”}; The advantage is that one can increase the rows as and when required. In C++ program nested loop is required for taking inputs for numeric type 2-D arrayswhereas generally single loop is used for taking inputs in character type 2-D arrays (i.e. forarray of strings).For string input gets ( ) function (which is defined in stdio.h header file) is normally preferredover cin>> operator since it can able to take the white space characters (tabs, spaces etc).Code segment: int Mat[4][5]; for (int i = 0; i < 4; i++) {-- Nested loop for (int j = 0; j < 5; j++) cin >> Mat[i][j]; -- Here i indicates rows & j indicatescolumns char days [7][11]; for (int i = 0; i < 7; i++) gets(days[i]);//Q1. Write a program to display the multiplication of two matrices#include<iostream.h>#include<conio.h>void main(){ clrscr(); int A[50][50],B[50][50],C[50][50]; int r1,c1,r2,c2,i,j,k; cout<<"nEnter the rows & columns for matrix A:"; cin>>r1>>c1; cout<<"nEnter the rows & columns for matrix B:"; cin>>r2>>c2; cout<<"nEnter the elements for matrix A:n"; for(i=0;i<r1;i++) for(j=0;j<c1;j++) { cout<<"element"<<i<<","<<j<<":"; cin>>A[i][j]; } cout<<"nEnter the elements for matrix B:n"; for(i=0;i<r2;i++) for(j=0;j<c2;j++) { cout<<"element"<<i<<","<<j<<":"; cin>>B[i][j]; Prepared By Sumit Kumar Gupta, PGT Computer Science
5. 5. Page 5 of 13 } if(c1!=r2) { cout<<"matrix multiplication is not possible!"; getch(); return; } else cout<<"multiplication is possible!"; //Multiplication for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { C[i][j]=0; for(k=0;k<r2;k++) { C[i][j]+=A[i][k]*B[k][j]; } } }cout<<"nMatrix A:n"; for(i=0;i<r1;i++) { cout<<"n"; for(j=0;j<c1;j++) cout<<A[i][j]; }cout<<"nMatrix B:n"; for(i=0;i<r2;i++) { cout<<"n"; for(j=0;j<c2;j++) cout<<B[i][j]; }cout<<"nProduct Matrix C:n"; for(i=0;i<c1;i++) { cout<<"n"; for(j=0;j<r2;j++) cout<<C[i][j]; }getch();}call by value & call by referenceA function can be invoked in two ways: call by value and call by reference Call by value Call by referenceIn call by value method the values of actual In call by reference a reference to the originalparameters (the parameters that appear in a variable is passed. A reference is an alias (i.e.function call statement i.e. the original values) a different name) for a predefined variable.are copied into the formal parameters (i.e. This means the original values are referredthe parameters that appear in function here. Here the called function does not createsdefinition). Here the called function creates its its own copy of original values, rather, it refersown copy of argument values for the original to the original values only by different names Prepared By Sumit Kumar Gupta, PGT Computer Science
6. 6. Page 6 of 13values and uses them i.e. it works with the i.e. the references i.e. it works with the originalduplicate data(s). data(s).In this method if there is any change(s) In this method if any change(s) occurred in theoccurred in the parameter(s), are not reflected parameter(s), are reflected back to the originalback to the original values. values.Example of call by value method:-#include<iostream.h>#include<conio.h>void main(){ clrscr(); void change(int); //prototype declaration int n; cout<<"n Enter any number:"; cin>>n; cout<<"noriginal value="<<n<<endl; change(n); // function call cout<<"nValue after function call="<<n<<endl; getch(); }//function definitionvoid change(int n1){ n1 = n1 + 5; //number is incremented by 5 cout<<"nValue in function definition="<<n1;}Output:Enter any number:5original value=5Value in function definition=10Value after function call=5 // Here the changes are not reflectedExample of call by reference method:-#include<iostream.h>#include<conio.h>void main(){ clrscr(); void change(int &); //prototype declaration (see the syntax) int n; cout<<"n Enter any number:"; cin>>n; cout<<"noriginal value="<<n<<endl; change(n); // function call cout<<"nValue after function call="<<n<<endl; getch(); } //function definition void change(int &n1) { n1 = n1 + 5; //number is incremented by 5 cout<<"nValue in function definition="<<n1; Prepared By Sumit Kumar Gupta, PGT Computer Science
7. 7. Page 7 of 13}Output:Enter any number:5original value=5Value in function definition=10Value after function call=10 //Here the changes are reflectedNote: The parameters are also known as arguments.Reference Variables:- Reference variables are the variables which refer to other variables by adifferent name. If we want to create another name of any variable then we have to use referencevariables;For ex:- int a =10; int &b = a; 10 0x8fc9fff4Both refer to the same memory areaWhere 10 is stored. a bPassing arrays to functions (numeric & string)Numeric array and string array can be passed as an argument to functions. Whenever we want topass a numeric array as an argument to functions we have to provide the array name (Since itis pointer to its base address i.e. holds the starting address of the array) along with its size.But in case of character array (i.e. for strings) we need to provide only the array name. Thisis because the string is terminated by null character in C++ so the size of the string isautomatically understandable by the compiler.Let us take examples to illustrate this:Q To display the highest & lowest marks of 10 students in a particular subject usingarray as an argument to a function#include<iostream.h>#include<conio.h>void main(){void ArrHL(int [ ],int); // prototype declarationint A[10],i;cout<<"nEnter the subject marks:n"; for(i=0;i<10;i++) { cout<<"marks "<<i+1<<":"; cin>>A[i]; } ArrHL(A,i); //function callgetch();}void ArrHL(int A1[],int n) //arguments are int array A and its size{ // [ ] indicates it can any size int H,L;for(int i=0;i<n;i++) Prepared By Sumit Kumar Gupta, PGT Computer Science
8. 8. Page 8 of 13 { L=A1[0]; H=A1[0]; if(A1[i]>H) H=A1[i]; if(A1[i]<L) L=A1[i]; } cout<<"nHighest Number="<<H<<endl; cout<<"nLowest Number="<<L;}outputEnter the subject marks:marks 1:2marks 2:6marks 3:8marks 4:121marks 5:17marks 6:19marks 7:0marks 8:23marks 9:25marks 10:29Highest Number=29Lowest Number=2Q. To find the reverse of a string and its length by passing a character array in afunction.#include<iostream.h>#include<conio.h>#include<stdio.h>void main(){clrscr();int strlencount(char []); // prototype declarationchar str[31];cout<<"nEnter the string:";gets(str);cout<<"nString Length= "<<strlencount(str); //function callgetch();}int strlencount(char str1[]) //argument is char array{ int len=0,i; for(i=0; str1[i]!=0; i++) len++; for(i=len-1;i>=0;i--) cout<<str1[i]; //We can also write cout<<str;return len;}Note: - Similarly 2-D array can also be passed as an argument to an array. Library Functions Prepared By Sumit Kumar Gupta, PGT Computer Science
9. 9. Page 9 of 13Library is a collection of subprograms used to develop other programs and software.The C++ library of functions stores functions of same category e.g. mathematicalfunctions, string functions, character functions etc. under separate files known asheader files.Header files provide function prototypes, definitions for library functions.Mathematical functions Header File (math.h)SL. Function Prototype (General Description ExampleNO. Form)1 exp double exp(double The exp( ) function returns the exp(2.0) gives arg) natural logarithm e raised to the the value e2. arg power.2 pow double pow(double The pow( ) function returns arg1 pow(3,2) gives arg1, double arg2) raised to arg2 power i.e. arg1 arg2 9. . A domain error occur if arg1 pow(3.0,0) gives = 0 and arg2 <= 0. Also if 1. arg1 < 0 and arg2 is not an pow(4.0,2.0) integer. gives 16.3 sqrt double sqrt (double The sqrt( ) function returns the sqrt(9) gives 3 num) square root of num. if num < 0 sqrt(81.0) gives domain error occurs. 9.04 fabs double fabs (double The fabs ( ) function returns the fabs(2.0) gives num) absolute value of num. 2.0. fabs(-3) gives 3.5 log 10 double log10(double The log10( ) function returns the log 10(1.0) gives num) base 10 logarithm for num. A base 10 domain error occurs if num is logarithm for 1.0 negative and a range error is occurs if the argument num is zero.6 log double log(double The log( ) function returns the log (1.0) gives num) natural logarithm for num. A natural logarithm domain error occurs if num is for 1.0 negative and a range error is occurs if the argument num is zero.7 fmod double fmod(double x, The fmod( ) function returns fmod(10.0,4.0) double y) reamainder of the division x/y. returns 2.0Note:- abs ( ) function is used to find the absolute value for integer numbers and mod() function is used to find the remainder when one integer is divided by another integernumber.String functions Header file string.hSL. Function Description ExampleNO.1 strcpy(s1,s2) This function copies character strcpy(“Vidyalaya”, string s2 to string s1. The s1 “Kendriya”) will give Kendriya. must have enough reserved elements to hold the string s2.2 strcat(s1,s2) This function concatenates strcat(“Computer”,”Science”) (merges) two strings. The will give ComputerScience. string s2 will be added at the end of string s1. The array s1 Prepared By Sumit Kumar Gupta, PGT Computer Science
10. 10. Page 10 of 13 must have enough reserved elements to hold the string s2.3 strcmp(s1,s2) This function compares the Strcmp(“KVS”,”KBS”); strings s1 with s2 on an It will return -1 alphabetic element by element basis.If s1>s2 then it return 1 if s1=s2 it return 0 And if s1<s2 it return -1 Character functionsHeader File - ctype.hFunction Description Exampleint isalnum(int,c) This functions returns nonzero value if its char c=’A’ Argument c is a letter or digit, if the if (isalnum( c)) character is not an alphanumeric then it cout<<”Alphanum”; returns zero.int isalpha(int,c) This functions returns nonzero value if its if (isalpha( c)) Argument c is a alphabet if the character is cout<<”Alphabet”; not an alphanumeric then it returns zero.int isalnum(int,c) This functions returns nonzero value if its if (isdigit( c)) Argument c is a digit, if the c is not digit cout<<”Digit”; then it returns zero.int islower(int,c) This functions returns nonzero value if its if (islower( c)) Argument c is in lowercase letter, otherwise cout<<”Lower it returns zero. case”;int isupper(c) This functions returns nonzero value if its if (isupper( c)) Argument c is in uppercase letter, otherwise cout<<”Upper it returns zero. case”;int toupper(int,c) This functions returns uppercase equivalent Char c=’a’ of c if c is already in upper case it remains cout<<toupper(c); unchange. output Aint tolower(int,c) This functions returns lowercase equivalent Char c=’A’ of c if c is already in lower case case it cout<<tolower(c); remains unchanged. output aQuestionsArray1.Write a program in C++ to interchange the values of the row and column.2 Write a user define function xyz() which takes a two dimensional array with size N rows and Ncolumnsas argument and store all 1)even in one dimensional array2) All odd in one dimensionalarray 3. display product of all the number except those which are not divisible by either 5 or 3.4. write a user define function unitdigit() which takes a two dimensional array with size N rowsand M columns as argument and store all i) unit digit ii) except unit digitIn two dimensional array. i.e A[2][3] = 200 213 56 657 Resultant array should be i) A[2][3] = 0 3 6 7 ii) A[2][3] = 20 21 5 655. Write a user define function repeat() which takes a two dimensional array with size N rowsand M columns as argument and convert all repeated element into zero. Prepared By Sumit Kumar Gupta, PGT Computer Science
11. 11. Page 11 of 136. Write a user define function convert() which takes a one dimensional array with size N asargument and convert it into two dimensional array.Suppose arr[6]= { 1,2,3,4,5,6} Resultant array should be Arr[6][6] = 2 1 4 36 5 2 1 4 36 0 2 1 4 30 0 2 1 4 00 0 2 1 000 0 2 0 0 00 0  Write a function in C++ to replace the repeating elements in an array by 0 . The zeros should be shifted to the end. Do not use parallel array . The order of the array should not change. (2) Eg : Array : 10 , 20 , 30 , 10 , 40 , 20 , 30 Result : 10 , 20 , 30 , 40 , 0 , 0 , 07. Write a function in C++ called shift( ) to rearrange the matrix as shown . Do not use parallelmatrix . (2) Original Matrix Rearranged Matrix 1 2 -3 -2 -3 -2 1 2 0 -1 2 1 -1 0 2 1 -3 9 -4 4 -3 -4 9 48. Find the output of the following program:#include <iostream.h>void modify(int arr[ ], int N){for (int I=1;I<N;I++) arr[ I-1]+=arr[ I ];}void main(){int P[]={1,2,3,4},Q[]={5,10,15,20,30};modify(P,4);modify(Q,5);for (int L=0;L<4;L++) cout<<P[L]<<”\$”;cout<<endl;for (L=0;L<5;L++) cout<<Q[L] <<”\$”;cout<<endl;}9. Find the output of the following program:#include <iostream.h>int a=5; Prepared By Sumit Kumar Gupta, PGT Computer Science
12. 12. Page 12 of 13void sample( int &x, int y , int *z) { a+=x; y*=a; *z=a+y; cout<<a<<” “ <<x<<” “<< y<<” “<<*z<<”n”; } void main() { clrscr(); int a =7 ,int b = 5 ; sample(::a , a , &b); cout<< ::a << “ “ << a <<” “<<b <<”n”; sample(::a , a , &b); cout<< ::a << “ “ << a <<” “<<b <<”n”; }10. Write a function in C++ to add new objects at the bottom of a binary file “TICKET.DAT”,assuming the binary file is containing the objects of the following class.class LOTTERY{int LotTicNo;char StateCode[5];public:void Enter(){cin>>LotTicNo;gets(StateCode);}void Display(){cout<<LotTicNo<<StateCode<<endl;}};11. Write a function in C++ that will read the contents of a file EXAM.DAT and display the details of those students whose marks>75. The binary file EXAM.DAT containing records of student. 2 class student { char roll [4]; char name[20]; int marks; public : void Read_Data ( ) ; // Entering data in to the file void Show_Date ( ); //Displaying the content of the file12 . Find the output of the following program. Assume that all required headers files have been included. 2 int funs (int &x, int y=10) { if (x%y == 10) return ++x; else return y-- ; } void main( ) { int p=20, q=23; q = funs(p,q); cout <<p<<”;”<<q<< endl; q = funs(p); Prepared By Sumit Kumar Gupta, PGT Computer Science
13. 13. Page 13 of 13 cout <<p<<”;”<<q<<endl;} Prepared By Sumit Kumar Gupta, PGT Computer Science