Understanding Arrays and Strings in Programming

chapter 2 n.w
1 / 35
Embed
Share

Dive into the world of arrays and strings in programming, starting with the definition and purpose of arrays, memory requirements, types of arrays, accessing particular slots, and initialization methods for one-dimensional arrays. Explore how arrays store multiple values efficiently and learn the syntax for working with them effectively.

  • Programming
  • Arrays
  • Strings
  • Memory
  • Initialization

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Chapter 2 Array and String

  2. Array Array Definition of Array Definition of Array : An array is a sequence or collection of the related data items that share a common name. Purpose Purpose : To store multiple values in a single variable but of same data type. Syntax Syntax : datatype arrayname[dim1][dim2] .[dimn]; where dimension indicates number of slots. e.g. int x[5]; => This indicates one dimensional array with 5 slots. 1 2 3 4 5 x

  3. Memory Requirement Memory Requirement Total no of bytes required for any array can be calculated as follows, bytes = size of given data type * dim1*dim2* .*dimn. e.g. int x[5] => bytes = 2*5=10 int y[5][3] => bytes = 2*5*3=30

  4. There are mainly two types of the array: There are mainly two types of the array: One Dimentional array Two Dimentional array One One Dimentional Array: Dimentional Array: A list of items can be given one variable name using only one dimension and such a variable is called a one dimensional array. Syntax: Syntax: datatype array datatype array- -name[size]; name[size]; Ex: Ex: int a[5]; int a[5];

  5. To access particular slot To access particular slot syntax: syntax: arrayname[logical slotno] arrayname[logical slotno] e.g. a[0] e.g. a[0]- - content of 0 content of 0th th slot(logical) slot(logical)

  6. If & is placed before the array name with slot no then it indicates the address of corresponding slot. Initialization of one Initialization of one dimentional arrays: dimentional arrays: After an array is declared, its element must be initialized. Otherwise, they will contain garbage . An array can be initialized at either of the following stages: 1. 1.At compile time At compile time 2. 2.At run time At run time 1. Compile time initialization: 1. Compile time initialization: Syntax: Syntax: Type array Type array- -name[size] = {list of values}; name[size] = {list of values}; The value in the list are separed by commas.

  7. Ex: Ex: int a[3] = {0,0,0} ; int a[3] = {0,0,0} ; int a[3] = {10, 20, 30, 40} ; int a[3] = {10, 20, 30, 40} ; will not work. It is illegal in C. counter array contain four element with initial value 1. Ex: Ex: int counter[] = {1,1,1,1} int counter[] = {1,1,1,1}

  8. 2. Run time initialization : 2. Run time initialization : An array can be explicitly initialized at run time. This approach is usually applied for initializing large arrays. Ex: Ex: for(i=0; i<100 ; i++) for(i=0; i<100 ; i++) { { if (i < 50 ) if (i < 50 ) sum[i] = 0.0; sum[i] = 0.0; else else sum[i] = 1.0; sum[i] = 1.0; } }

  9. Ex: Ex: int x[3]; int x[3]; Will initialize array elements with the values entered through the keyboard. scanf ( %d%d%d , &x[0], &x[1], &x[2] ) ; scanf ( %d%d%d , &x[0], &x[1], &x[2] ) ;

  10. Example 1 : Accept n nos. in an array and display the sum and average of these n nos. #include<stdio.h> #include<conio.h> void main() { int i,arr[20],n; float sum=0; printf("Enter the value for n (max 20): "); scanf("%d",&n); printf("Enter %d numbers : ",n); for(i=0;i<n;i++) { scanf("%d",&arr[i]); sum += arr[i]; } printf("The sum of the numbers is : %d\n",sum); printf("The average of the numbers is : %.3f\n",sum/n); getch(); }//main Output: Output: Enter the value for n (max 20): 6 Enter 6 numbers : 25 67 89 12 10 45 The sum of the numbers is : 248 The average of the numbers is : 41.3

  11. Example 2 : Accept n elements in an array and sort the array in ascending order. #include<stdio.h> #include<conio.h> void main() { int i,arr[20],n,j,temp; printf("Enter the value for n (max 20): "); scanf("%d",&n); printf("Enter %d numbers : ",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(arr[i] > arr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } printf("\nThe elements in ascending order are :\n"); for(i=0;i<n;i++) printf("%d\t",arr[i]); Output: Output: Enter the value for n (max 20): 6 Enter 6 numbers : 25 67 89 12 10 45 The elements in ascending order are : 10 12 25 45 67 89

  12. Example 3 : Accept n elements in an array and find the sum of all odd numbers and even numbers. #include<stdio.h> #include<conio.h> void main() { int i,arr[20],n,sum1=0,sum2=0; printf("Enter the value for n (max 20): "); scanf("%d",&n); printf("Enter %d numbers : ",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=0;i<n;i++) { if(arr[i]%2 == 0) sum1+=arr[i]; else sum2+=arr[i]; }//for printf("The sum of even numbers is %d\n",sum1); printf("The sum of odd numbers is %d\n",sum2); getch(); }//main Output: Output: Enter the value for n (max 20): 10 Enter 10 numbers : 34 11 10 5 7 32 12 66 99 3 The sum of even numbers is 154 The sum of odd numbers is 125

  13. TWO TWO DIMENTIONAL ARRAY: DIMENTIONAL ARRAY: If you want to store data into table or matrix form at that time you can use the two dimensional array. Declaration of two Declaration of two dimentional dimentional array: array: Syntax : Syntax : data_type data_type array array- -name[dim1][dim2]; name[dim1][dim2]; Where dim1 indicates total rows and dim2 indicates total columns. Where dim1 indicates total rows and dim2 indicates total columns. Ex: Ex: ITEM 1 SALES MAN 1 310 SALES MAN 2 210 SALES MAN 3 405 SALES MAN 4 260 ITEM2 275 190 235 300 ITEM 3 365 325 240 380

  14. Memory representation of the two Memory representation of the two dimentional column 0 column 1 column 0 column 1 [0][0] [0][0] Row 0 Row 0 [1][0] [1][0] Row 1 Row 1 [2][0] [2][0] Row Row 2 2 [3][0] [3][0] Row 3 Row 3 310 dimentional array for v[4][3] . array for v[4][3] . column2 column2 [0][1] [0][1] 275 [0][2] [0][2] 365 310 [1][1] [1][1] [1][2] [1][2] 10 190 325 [2][1] [2][1] 235 [2][2 [2][2] ] 240 405 [3][1] [3][1] 275 [3][2] [3][2] 365

  15. Initializing two dimentional array: Initializing two dimentional array: Ex: int table[2][3] = {0,0,0,1,1,1}; Ex: int table[2][3] = {0,0,0,1,1,1}; int table[2][3] = { } ; {0,0,0}, {1,1,1}

  16. Initializing two dimentional array: Initializing two dimentional array: When the array is completely initialized with all values, we need not specify the size of the first dimension. That is, the statement is permitted. int table[][3] = { }; {0,0,0} , {1,1,1)

  17. If the value is missing in an initializes, they are automatically set to zero. Ex: int table[2][3] ={ Ex: int table[2][3] ={ } ; } ; int m[3][5] = { 0, 0 }; int m[3][5] = { 0, 0 }; or or int m[3][5] = { {0} , { 0} }; int m[3][5] = { {0} , { 0} }; {1,1} , {1,1} , {2} {2}

  18. Example 1 : Write a program for addition and subtraction of two matrices. #include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],i,j,r,c; printf( \n Enter no of rows and columns ); scanf( %d%d ,&r,&c); printf("Enter %d elements of first matrix\n ,r*c); for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",&a[i][j]); printf("Enter %d elements of second matrix \n ,r*c);

  19. for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",&b[i][j]); for(i=0;i<r;i++) for(j=0;j<c;j++) c[i][j] = a[i][j]+b[i][j]; printf("The addition of the two matrices is : \n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("%d\t",c[i][j]); printf("\n"); }

  20. for(i=0;i<r;i++) for(j=0;j<c;j++) c[i][j] = a[i][j]-b[i][j]; printf("The subtraction of the two matrices is : \n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("%d\t",c[i][j]); printf("\n"); } getch(); }

  21. Enter no of rows and columns 3 3 Enter 9 elements of first matrix 23 4 67 8 6 21 19 10 5 Enter 9 elements of second matrix 3 45 21 39 10 16 14 12 11 The addition of the two matrices is : 26 49 88 47 16 37 33 22 16 The subtraction of the two matrices is : 20 -41 46 -31 -4 5 5 -2 -6

  22. Example 2 :Write a program to display the transpose of entered matrix #include<stdio.h> #include<conio.h> void main() { int a[5][5],i,j,r,c,b[5][5]; clrscr(); printf( \n Enter no of rows and columns ); scanf( %d%d ,&r,&c); printf("Enter %d elements of matrix \n r*c); for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",&a[i][j]); for(i=0;i<r;i++) for(j=0;j<c;j++) b[j][i]=a[i][j]);

  23. printf("The transpose of the matrix is : \n\n"); for(i=0;i<c;i++) { for(j=0;j<r;j++) printf("%d\t ,b[i][j]); printf("\n"); } getch(); } Output: Output: Enter no of rows and columns 3 2 Enter 6 elements of matrix 12 67 90 11 34 77 The transpose of the matrix is : 12 90 34 67 11 77

  24. String String What is a String : What is a String : String is a group of characters. String is a group of characters. Any group of character defined between double Any group of character defined between double quotation mark is a constant string. quotation mark is a constant string. Ex: printf( Hello How are you ); output : Hello How are you If you want to include double quotes with string than also it is possible. Ex: printf( \ Hello How are you \ ); output : Hello How are you

  25. Declaring and Initialising String Variable : Declaring and Initialising String Variable : A String Variable is always declared as an array : Syntax : char string_name[size]; where size determines the number of character in the string. Size should be maximum number of the character + 1. Ex: char city[10]; char name[30];

  26. Initialization of string variable : Initialization of string variable : char array may be initialized when they are declared. You can initialized char array with two form: char city[9] = New York ; char city[9] = { N , e , w , , Y , o , r , k , \0 };

  27. C also permit us to initialize character array without specifying the number of elements. Ex: Ex: char string[] = { G , O , O , D , \0 }; It defines the string as five elements array.

  28. Reading String : Reading String : Ex: Ex: char address[15]; scanf( %s ,address); (& sign is not included before address) The problem with the scanf() function is that it terminates its input on the first white space it finds. Ex: Ex: If input string is New York then in address array stores only New . After New, string will be terminated. For this reason to read the string gets() function is used which reads white spaces also. Syntax: Syntax: gets(arrayname); Ex. gets(address);

  29. Writing string to screen : Writing string to screen : We have used printf() function with %s format to print the string to the screen. Ex: Ex: printf( %s ,name); We can use puts() function to display the string. syntax : e.g. syntax : puts(stringname); e.g. puts(name);

  30. Features of the %s format specification : Features of the %s format specification : (1) The integer value on the right side of the decimal point specifies the number of character to be printed. Ex: %10.4s specifies 4 character printed . (2) When the number of character to be printed is specified by zero, nothing is printed. Ex: %10.0s (3) The minus sign in the specification causes the string to be printed left side. Ex: %-10.4s 4 character printed left side.

  31. Another nice features for printing output is: Another nice features for printing output is: printf( %*.*s\n ,w,d,string); prints the first d characters of the string in the field width of w. Write the program for writing string using %s format : void main() { char country[15] = United Kingdom printf( %15s \n ,country); printf( %5s \n ,country); printf( %15.6s \n ,country); printf( %-15.6s \n ,country); printf( %15.0s \n ,country); printf( %0.3s \n ,country); } Output : Output : United Kingdom United Kingdom United United United United United United Uni Uni

  32. The C library provides a function which converts string of digits into their integer value. Ex: number = 1988 ; year = atoi(number); String Handling function : String Handling function : There are mainly four types of string handling function: 1. strcat() Concatenation of two string 2. strcmp() Compares two string 3. strcpy() copies one string over another string 4. strlen() finds the length of the string.

  33. strcat() strcat() : - Using this function you can concat two string: syntax : syntax : strcat(string1,string2); Ex: str1 = Very \0 str2 = Good\0 It also allows to concat three string together Ex: strcat(strcat(str1,str2),str3); output : Very GoodBad str3 = Bad\0 strcat(str1,str2); output : output : Very Good\0

  34. strcmp() : strcmp() : This function compares two string If both are equal then it returns 0 and if they are not equal then it will return numeric difference between the nonmatching character. Ex: Ex: strcmp( their , there ); will return numeric difference between ASCII i and r .

  35. strcpy () : strcpy () : using this function we can copy contents of one string to contents of another string. syntax : strcpy(str1,str2); Ex: Ex: str1 = Very \0 str2 = Good\0 strcpy(str1,str2); will store Good\0 in str1. strlen() : strlen() : This function is used to find the length of the string. n = strlen(string); where n is an integer variable. Ex: Ex: str1 = Very \0 will store 5 to n.

Related


More Related Content