Arrays and library functions
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

Arrays and library functions

  • 583 views
Uploaded on

This for the students of computer science and for those who want to learn about the concepts

This for the students of computer science and for those who want to learn about the concepts

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
583
On Slideshare
583
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
21
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 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) Twodimensional 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 types of elements referenced by a common name. The elements of the 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]. numbers which are within [ ] ) always starts with number 0 not 1 in the locations of the elements within the array. a collection of similar are referred by their Array subscripts ( the C++. Subscripts are Memory representation of 1-D array Let us take the above example which is int A[5]; A[0] Starting address A[1] 25 A[2] -13 A[3] 44 A[4] 0 Location 10 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. 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 onedimensional 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 str[0] K Location in the array str[8] e n d r i y a V i d y a l a y str[18] 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. Page 3 of 13 Columns 0 1 2 3 n-1 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 (7) 0 1 2 3 4 5 6 M T W T F S S 1 O U E H R A U 2 3 4 N E D U I T N D S N R D U D A D E S A R A 5 Y A S D Y D Y 6 0 Y D A 0 A 0 7 8 0 A Y Y 0 Y 9 10 0 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. 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, 2, 8, 3, 27, 4, 64 }; -- rows should be left blank 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 arrays whereas generally single loop is used for taking inputs in character type 2-D arrays (i.e. for array of strings). For string input gets ( ) function (which is defined in stdio.h header file) is normally preferred over 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 indicates columns 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. 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 reference A function can be invoked in two ways: call by value and call by reference Call by value In call by value method the values of actual parameters (the parameters that appear in a function call statement i.e. the original values) are copied into the formal parameters (i.e. the parameters that appear in function definition). Here the called function creates its own copy of argument values for the original Call by reference In call by reference a reference to the original variable is passed. A reference is an alias (i.e. a different name) for a predefined variable. This means the original values are referred here. Here the called function does not creates its own copy of original values, rather, it refers to the original values only by different names Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 6. Page 6 of 13 values and uses them i.e. it works with the duplicate data(s). i.e. the references i.e. it works with the original data(s). In this method if there is any change(s) occurred in the parameter(s), are not reflected back to the original values. In this method if any change(s) occurred in the parameter(s), are reflected back to the original 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 definition void change(int n1) { n1 = n1 + 5; //number is incremented by 5 cout<<"nValue in function definition="<<n1; } Output: Enter any number:5 original value=5 Value in function definition=10 Value after function call=5 // Here the changes are not reflected Example 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. Page 7 of 13 } Output: Enter any number:5 original value=5 Value in function definition=10 Value after function call=10 //Here the changes are reflected Note: The parameters are also known as arguments. Reference Variables:- Reference variables are the variables which refer to other variables by a different name. If we want to create another name of any variable then we have to use reference variables; For ex:int a =10; 0x8fc9fff4 int &b = a; 10 Both refer to the same memory area Where 10 is stored. a b Passing arrays to functions (numeric & string) Numeric array and string array can be passed as an argument to functions. Whenever we want to pass a numeric array as an argument to functions we have to provide the array name (Since it is 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. This is because the string is terminated by null character in C++ so the size of the string is automatically 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 using array as an argument to a function #include<iostream.h> #include<conio.h> void main() { void ArrHL(int [ ],int); // prototype declaration int 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 call getch(); } 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. 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; } output Enter the subject marks: marks 1:2 marks 2:6 marks 3:8 marks 4:121 marks 5:17 marks 6:19 marks 7:0 marks 8:23 marks 9:25 marks 10:29 Highest Number=29 Lowest Number=2 Q. To find the reverse of a string and its length by passing a character array in a function. #include<iostream.h> #include<conio.h> #include<stdio.h> void main() { clrscr(); int strlencount(char []); // prototype declaration char str[31]; cout<<"nEnter the string:"; gets(str); cout<<"nString Length= "<<strlencount(str); //function call getch(); } 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. Page 9 of 13 Library is a collection of subprograms used to develop other programs and software. The C++ library of functions stores functions of same category e.g. mathematical functions, string functions, character functions etc. under separate files known as header files. Header files provide function prototypes, definitions for library functions. Mathematical functions Header File (math.h) SL. NO. 1 Function 2 pow double pow(double arg1, double arg2) 3 sqrt double sqrt (double num) 4 fabs double fabs (double num) 5 log 10 double log10(double num) 6 log double log(double num) 7 fmod double fmod(double x, double y) exp Prototype (General Form) double exp(double arg) Description Example The exp( ) function returns the natural logarithm e raised to the arg power. The pow( ) function returns arg1 raised to arg2 power i.e. arg1 arg2 . A domain error occur if arg1 = 0 and arg2 <= 0. Also if arg1 < 0 and arg2 is not an integer. The sqrt( ) function returns the square root of num. if num < 0 domain error occurs. The fabs ( ) function returns the absolute value of num. exp(2.0) gives the value e2. The log10( ) function returns the base 10 logarithm for num. A domain error occurs if num is negative and a range error is occurs if the argument num is zero. The log( ) function returns the natural logarithm for num. A domain error occurs if num is negative and a range error is occurs if the argument num is zero. The fmod( ) function returns reamainder of the division x/y. pow(3,2) gives 9. pow(3.0,0) gives 1. pow(4.0,2.0) gives 16. sqrt(9) gives 3 sqrt(81.0) gives 9.0 fabs(2.0) gives 2.0. fabs(-3) gives 3. log 10(1.0) gives base 10 logarithm for 1.0 log (1.0) gives natural logarithm for 1.0 fmod(10.0,4.0) returns 2.0 Note:- 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 integer number. String functions Header file string.h SL. NO. 1 Function Description Example strcpy(s1,s2) strcpy(“Vidyalaya”, “Kendriya”) will give Kendriya. 2 strcat(s1,s2) This function copies character string s2 to string s1. The s1 must have enough reserved elements to hold the string s2. This function concatenates (merges) two strings. The string s2 will be added at the end of string s1. The array s1 strcat(“Computer”,”Science”) will give ComputerScience. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 10. Page 10 of 13 3 strcmp(s1,s2) must have enough reserved elements to hold the string s2. This function compares the strings s1 with s2 on an 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 Strcmp(“KVS”,”KBS”); It will return -1 Character functions Header File - ctype.h Function int isalnum(int,c) int isalpha(int,c) int isalnum(int,c) int islower(int,c) int isupper(c) int toupper(int,c) int tolower(int,c) Description This functions returns nonzero value if its Argument c is a letter or digit, if the character is not an alphanumeric then it returns zero. This functions returns nonzero value if its Argument c is a alphabet if the character is not an alphanumeric then it returns zero. This functions returns nonzero value if its Argument c is a digit, if the c is not digit then it returns zero. This functions returns nonzero value if its Argument c is in lowercase letter, otherwise it returns zero. This functions returns nonzero value if its Argument c is in uppercase letter, otherwise it returns zero. This functions returns uppercase equivalent of c if c is already in upper case it remains unchange. This functions returns lowercase equivalent of c if c is already in lower case case it remains unchanged. Example char c=’A’ if (isalnum( c)) cout<<”Alphanum”; if (isalpha( c)) cout<<”Alphabet”; if (isdigit( c)) cout<<”Digit”; if (islower( c)) cout<<”Lower case”; if (isupper( c)) cout<<”Upper case”; Char c=’a’ cout<<toupper(c); output A Char c=’A’ cout<<tolower(c); output a Questions Array 1.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 N columnsas argument and store all 1)even in one dimensional array2) All odd in one dimensional array 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 rows and M columns as argument and store all i) unit digit ii) except unit digit In 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 65 5. Write a user define function repeat() which takes a two dimensional array with size N rows and M columns as argument and convert all repeated element into zero. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 11. Page 11 of 13 6. Write a user define function convert() which takes a one dimensional array with size N as argument 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 , 0 7. Write a function in C++ called shift( ) to rearrange the matrix as shown . Do not use parallel matrix . (2) Original Matrix 1 0 -3 2 -1 9 -3 2 -4 Rearranged Matrix -2 1 4 -3 -1 -3 -2 0 -4 1 2 9 2 1 4 8. 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. Page 12 of 13 void 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 file 12 . 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. Page 13 of 13 cout <<p<<”;”<<q<<endl; } Prepared By Sumit Kumar Gupta, PGT Computer Science