C language (Collected By Dushmanta)

9,080 views

Published on

Published in: Education, Technology
1 Comment
27 Likes
Statistics
Notes
No Downloads
Views
Total views
9,080
On SlideShare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
695
Comments
1
Likes
27
Embeds 0
No embeds

No notes for slide

C language (Collected By Dushmanta)

  1. 1. Programming in CObjectives In this session, you will learn to: Identify the benefits and features of C language Use the data types available in C language Identify the structure of C functions Use input-output functions Use constructs Ver. 1.0 Slide 1 of 53
  2. 2. Programming in CIdentifying the Benefits and Features of C Language Ken Thompson developed a new language called B. B language was interpreter-based, hence it was slow. Dennis Ritchie modified B language and made it a compiler-based language. The modified compiler-based B language is named as C. Ver. 1.0 Slide 2 of 53
  3. 3. Programming in CC as a Second and Third Generation Language C language: Possesses powerful low-level features of second generation languages. Provides loops and constructs available in third generation languages. Is very powerful and flexible. Ver. 1.0 Slide 3 of 53
  4. 4. Programming in CBlock Structured Language - An Advantage for Modular Programming C language: Offers all essentials of structured programming. Has functions that work along with other user-developed functions and can be used as building blocks for advanced functions. Offers only a handful of functions, which form the core of the language. Has rest of the functions available in libraries. These functions are developed using the core functions. Ver. 1.0 Slide 4 of 53
  5. 5. Programming in CFeatures of the C Language The features that make C a widely-used language are: Pointers: Allows reference to a memory location by a name. Memory Allocation: Allows static as well as dynamic memory allocation. Recursion: Is a process in which a functions calls itself. Bit Manipulation: Allows manipulation of data in its lowest form of storage. Ver. 1.0 Slide 5 of 53
  6. 6. Programming in CUsing the Data Types Available in C language The types of data structures provided by C can be classified under the following categories: Fundamental data types Derived data types Ver. 1.0 Slide 6 of 53
  7. 7. Programming in CFundamental Data Types Fundamental Data Types: Are the data types at the lowest level. Are used for actual data representation in the memory. Are the base for other data types. Have machine dependent storage requirement. Are of the following three types: char int float Ver. 1.0 Slide 7 of 53
  8. 8. Programming in CFundamental Data Types (Contd.) The storage requirement for fundamental data types can be represented with the help of the following table. Data Number of bytes on a Minimum Maximum 32-byte machine char 1 -128 127 int 4 -2^31 (2^31) - 1 float 4 6 digits of precision 6 digits of precision Ver. 1.0 Slide 8 of 53
  9. 9. Programming in CDerived Data Types Derived Data Types: Are represented in memory as fundamental data type. Some derived data types are: short int long int double float Ver. 1.0 Slide 9 of 53
  10. 10. Programming in CDerived Data Types (Contd.) The storage requirement for derived data types can be represented with the help of the following table. Data Number of bytes Minimum Maximum on a 32-byte machine short int 2 -2^15 (2^15) - 1 long int 4 -2^31 (2^31) - 1 double float 8 12 digits of precision 6 digits of precision Ver. 1.0 Slide 10 of 53
  11. 11. Programming in CDefining Data The syntax for defining data is: [data type] [variable name],...; Declaration is done in the beginning of a function. Definition for various data types is shown in the following table. Data definition Data type Memory defined Size (bytes) Value assigned char a, c; char a 1 - c 1 - char a = Z; char a 1 Z int count; int count 4 - int a, count =10; int a 4 - count 4 10 float fnum; float fnum 4 - float fnum1, float fnum1 4 - fnum2 = 93.63; fnum2 4 93.63 Ver. 1.0 Slide 11 of 53
  12. 12. Programming in CPractice: 1.1 Write the appropriate definitions for defining the following variables: 1. num to store integers. 2. chr to store a character and assign the character Z to it. 3. num to store a number and assign the value 8.93 to it. 4. i, j to store integers and assign the value 0 to j. Ver. 1.0 Slide 12 of 53
  13. 13. Programming in CPractice: 1.1 (Contd.) Solution: 1. int num; 2. char chr=‘Z‘; 3. float num = 8.93; 4. int i, j=0; Ver. 1.0 Slide 13 of 53
  14. 14. Programming in CDefining Data (Contd.) Defining Strings: Syntax: char (variable) [(number of bytes)]; Here number of bytes is one more than the number of characters to store. To define a memory location of 10 bytes or to store 9 valid characters, the string will be defined as follows: char string [10]; Ver. 1.0 Slide 14 of 53
  15. 15. Programming in CPractice: 1.2 Write the appropriate definitions for defining the following strings: 1. addrs to store 30 characters. 2. head to store 14 characters. Ver. 1.0 Slide 15 of 53
  16. 16. Programming in CPractice: 1.2 (Contd.) Solution: 1. char addrs[31]; 2. char head[15]; Ver. 1.0 Slide 16 of 53
  17. 17. Programming in CIdentifying the Structure of C Functions In C language, the functions can be categorized in the following categories: Single-level functions Multiple-level functions Ver. 1.0 Slide 17 of 53
  18. 18. Programming in CSingle Level Functions Single Level Functions: Consider the following single-level function: main() { /*print a message*/ printf("Welcome to C"); } In the preceding function: main(): Is the first function to be executed. (): Are used for passing parameters to a function. {}: Are used to mark the beginning and end of a function. These are mandatory in all functions. /* */: Is used for documenting various parts of a function. Ver. 1.0 Slide 18 of 53
  19. 19. Programming in CSingle Level Functions (Contd.) Semicolon (;): Is used for marking the end of an executable line. printf(): Is a C function for printing (displaying) constant or variable data. Ver. 1.0 Slide 19 of 53
  20. 20. Programming in CPractice: 1.3 Identify any erroneous or missing component(s) in the following functions: 1. man() { printf("This function seems to be okay") } 2. man() { /*print a line*/ printf("This function is perfect―; } Ver. 1.0 Slide 20 of 53
  21. 21. Programming in CPractice: 1.3 (Contd.) 3. main() } printf("This has got to be right"); { 4. main() { This is a perfect comment line printf("Is it okay?"); } Ver. 1.0 Slide 21 of 53
  22. 22. Programming in CPractice: 1.3 (Contd.) Solution: 1. man instead of main() and semi-colon missing at the end of the printf() function. 2. mam instead of main() and ‘)’ missing at the end of the printf() function. 3. ‘}’ instead of ‘{‘ for marking the beginning of the function and ‘{’ instead of ‘}‘ for marking the end of the function. 4. Comment line should be enclose between /* and */. Ver. 1.0 Slide 22 of 53
  23. 23. Programming in CMultiple Level Functions The following example shows functions at multiple levels - one being called by another: main () { /* print a message */ printf ("Welcome to C."); disp_msg (); printf ("for good learning"); } disp_msg () { /* print another message */ printf ("All the best"); } Ver. 1.0 Slide 23 of 53
  24. 24. Programming in CMultiple Level Functions (Contd.) The output of the preceding program is: Welcome to C. All the best for good learning. In the preceding program: main(): Is the first function to be executed. disp_msg(): Is a programmer-defined function that can be independently called by any other function. (): Are used for passing values to functions, depending on whether the receiving function is expecting any parameter. Semicolon (;): Is used to terminate executable lines. Ver. 1.0 Slide 24 of 53
  25. 25. Programming in CPractice: 1.4 Identify any erroneous or missing component(s) in the following functions: a. print_msg() { main(); printf(―bye‖); } main() { printf(―This is the main function‖);} b. main() { /*call another function*/ dis_error(); } disp_err(); { printf(―Error in function‖);} Ver. 1.0 Slide 25 of 53
  26. 26. Programming in CPractice: 1.4 (Contd.) Solution: a. main() is always the first function to be executed. Further execution of the program depends on functions invoked from main(). Here, after executing printf(), the program terminates as no other function is invoked. The function print_msg is not invoked, hence it is not executed. b. The two functions, dis_error() and disp_error, are not the same because the function names are different. Ver. 1.0 Slide 26 of 53
  27. 27. Programming in CUsing the Input-Output Functions The C environment and the input and output operations are shown in the following figure. Standard Input Device (stdin) Standard Output Device (stdout) C Environment Standard Error Device (stderr) Ver. 1.0 Slide 27 of 53
  28. 28. Programming in CUsing the Input-Output Functions (Contd.) These are assumed to be always linked to the C environment: stdin - refers to keyboard stdin - refers to keyboard stdout - refers to VDU stderr - refers to VDU Input and output takes place as a stream of characters. Each device is linked to a buffer through which the flow of characters takes place. After an input operation from the standard input device, care must be taken to clear input buffer. Ver. 1.0 Slide 28 of 53
  29. 29. Programming in CCharacter-Based Input-Output Functions Character-Based Input-Output Functions are: getc() putc() getchar() putchar() The following example uses the getc() and putc() functions: # include < stdio.h> /* function to accept and display a character*/ main () {char alph; alph = getc (stdin); /* accept a character */ fflush (stdin); /* clear the stdin buffer*/ putc (alph, stdout); /* display a character*/ } Ver. 1.0 Slide 29 of 53
  30. 30. Programming in CCharacter-Based Input-Output Functions (Contd.) The following example uses the getchar() and putchar() functions: # include < stdio.h > /* function to input and display a character using the function getchar() */ main () { char c; c = getchar (); fflush (stdin); /* clear the buffer */ putchar (c); } Ver. 1.0 Slide 30 of 53
  31. 31. Programming in CPractice: 1.5 1. Write a function to input a character and display the character input twice. Ver. 1.0 Slide 31 of 53
  32. 32. Programming in CPractice: 1.5 (Contd.) Solution: Ver. 1.0 Slide 32 of 53
  33. 33. Programming in CPractice: 1.6 1. Write a function to accept and store two characters in different memory locations, and to display them one after the other using the functions getchar() and putchar(). Ver. 1.0 Slide 33 of 53
  34. 34. Programming in CPractice: 1.6 (Contd.) Solution: /* function to accept and display two characters*/ #include<stdio.h> main() { char a, b; a=getchar(); fflush(stdin); b=getchar(); fflush(stdin); putchar(a); putchar(b); } Ver. 1.0 Slide 34 of 53
  35. 35. Programming in CString-Based Input-Output Functions String-based input-output functions are: gets() puts() The following example uses the gets() and puts() functions: # include < stdio.h > /* function to accept and displaying */ main () { char in_str {21}; /* display prompt */ puts ("Enter a String of max 20 characters"); gets (in_str); /* accept string */ fflush (stdin); /* clear the buffer */ puts (in_str); /* display input string */ } Ver. 1.0 Slide 35 of 53
  36. 36. Programming in CPractice: 1.7 1. Write a function that prompts for and accepts a name with a maximum of 25 characters, and displays the following message. Hello. How are you? (name) 2. Write a function that prompts for a name (up to 20 characters) and address (up to 30 characters) and accepts them one at a time. Finally, the name and address are displayed in the following way. Your name is: (name) Your address is: (address) Ver. 1.0 Slide 36 of 53
  37. 37. Programming in CPractice: 1.7 (Contd.) Solution: Ver. 1.0 Slide 37 of 53
  38. 38. Programming in CUsing Constructs There are two types of constructs in C language: Conditional constructs Loop constructs Ver. 1.0 Slide 38 of 53
  39. 39. Programming in CConditional Constructs Conditional Constructs: Requires relation operators as in other programming language with a slight change in symbols used for relational operators. The two types of conditional constructs in C are: if..else construct switch…case construct Ver. 1.0 Slide 39 of 53
  40. 40. Programming in CConditional Constructs (Contd.) The Syntax of the if..else construct is as follows: if (condition) { statement 1 ; statement 2 ; : } else { statement 1 ; statement 2 ; : } Ver. 1.0 Slide 40 of 53
  41. 41. Programming in CPractice: 1.8 1. Write a function that accepts one-character grade code, and depending on what grade is input, display the HRA percentage according to the following table. Grade HRA % A 45% B 40% C 30% D 25% Ver. 1.0 Slide 41 of 53
  42. 42. Programming in CPractice: 1.8 (Contd.) Identify errors, if any, in the following function: #include<stdio.h> /*function to check if y or n is input*/ main() { char yn; puts("Enter y or n for yes/no"); yn = getchar(); fflush(stdin); if(yn=‘y‘) puts("You entered y"); else if(yn=‗n) puts("You entered n"); else puts("Invalid input"); } Ver. 1.0 Slide 42 of 53
  43. 43. Programming in CPractice: 1.8 (Contd.) Solution: Ver. 1.0 Slide 43 of 53
  44. 44. Programming in CConditional Constructs (Contd.) Syntax of switch…case construct: switch (variable) { case 1 : statement1 ; break ; case 2 : statement 2 ; : : break; default : statement } Ver. 1.0 Slide 44 of 53
  45. 45. Programming in CPractice: 1.9 Write a function to display the following menu and accept a choice number. If an invalid choice is entered then an appropriate error message must be displayed, else the choice number entered must be displayed. Menu 1. Create a directory 2. Delete a directory 3. Show a directory 4. Exit Your choice: Ver. 1.0 Slide 45 of 53
  46. 46. Programming in CPractice: 1.9 (Contd.) Solution: Ver. 1.0 Slide 46 of 53
  47. 47. Programming in CLoop Constructs The two types of conditional constructs in C are: while loop construct. do..while construct. The while loop construct has the following syntax: while (condition in true) { statement 1 ; loop statement 2 ; body } Used to iterate a set of instructions (the loop body) as long as the specified condition is true. Ver. 1.0 Slide 47 of 53
  48. 48. Programming in CLoop Constructs (Contd.) The do..while loop construct: The do..while loop is similar to the while loop, except that the condition is checked after execution of the body. The do..while loop is executed at least once. The following figure shows the difference between the while loop and the do...while loop. while do while False Execute Evaluate Body of Condition Loop True Execute False Body of Evaluate Loop Condition True Ver. 1.0 Slide 48 of 53
  49. 49. Programming in CPractice: 1.10 1. Write a function to accept characters from the keyboard until the character ‘!’ is input, and to display whether the total number of non-vowel characters entered is more than, less than, or equal to the total number of vowels entered. Ver. 1.0 Slide 49 of 53
  50. 50. Programming in CPractice: 1.10 (Contd.) Solution: Ver. 1.0 Slide 50 of 53
  51. 51. Programming in CSummary In this session, you learned that: C language was developed by Ken Thompson and Dennis Ritchie. C language combines the features of second and third generation languages. C language is a block structured language. C language has various features that make it a widely-used language. Some of the important features are: Pointers Memory Allocation Recursion Bit-manipulation Ver. 1.0 Slide 51 of 53
  52. 52. Programming in CSummary (Contd.) The types of data structures provided by C can be classified under the following categories: Fundamental data types: Include the data types, which are used for actual data representation in the memory. Derived data types: Are based on fundamental data types. Fundamental data types: char, int, and float Some of the derived data types are: short int, long int, and double float Definition of memory for any data, both fundamental and derived data types, is done in the following format: [data type] [variable name],...; Ver. 1.0 Slide 52 of 53
  53. 53. Programming in CSummary (Contd.) In C language, the functions can be categorized in the following categories: Single-level functions Multiple-level functions For standard input-output operations, the C environment uses stdin, stdout, and stderr as references for accessing the devices. There are two types of constructs in C language: Conditional constructs Loop constructs Ver. 1.0 Slide 53 of 53
  54. 54. Programming in CObjectives In this session, you will learn to: Work with operators Use loops Use formatted input-output functions Ver. 1.0 Slide 54 of 53
  55. 55. Programming in CWorking with Operators An operator: Is a symbol used to command the computer to do mathematical or logical manipulations. Operates on data and variables. C has a rich set of operators, which can be classified into following various categories: Relational operators Logical operators Unary operators Binary operators Ternary operator Compound assignment operators Increment/Decrement operators Ver. 1.0 Slide 55 of 53
  56. 56. Programming in CPractice: 2.1 Write a function that accepts either y or n only as input. For any other character input, an appropriate error message should be displayed and the input is accepted again. Ver. 1.0 Slide 56 of 53
  57. 57. Programming in CPractice: 2.1 (Contd.) Solution: #include<stdio.h> main() { char yn; do { puts(―Enter y/n (Yes/No)‖); yn=getchar (); fflush (stdin); if(yn!=‘y‘ && yn!=‘n‘) puts(―Invalid input‖); } while(yn!=‘y‘ && yn!=‘n‘); } Ver. 1.0 Slide 57 of 53
  58. 58. Programming in CUnary Operators Unary Operators: Operates on a single operand. Prefixed to an integer constant. Tells the compiler to reverse the sign by subtracting the value (or variable) from zero. Has the same effect as the – sign, which is used to indicate a number less than zero, for example -12. Ver. 1.0 Slide 58 of 53
  59. 59. Programming in CPractice: 2.2 Which of the following are valid? 1. valuea=-12; /* valuea is int* / 2. valuea = - valueb – 12 /* valuea and valueb both are int */ Ver. 1.0 Slide 59 of 53
  60. 60. Programming in CPractice: 2.2 (Contd.) Solution: 1. Valid 2. Valid Ver. 1.0 Slide 60 of 53
  61. 61. Programming in CBinary Operators Binary Operators: Operate on two operands. Are as follows: + (add) - (subtract) * (multiply) / (divide) % (modulo) Ver. 1.0 Slide 61 of 53
  62. 62. Programming in CPractice: 2.3 In the following set of statements: char ch; ch=‘S‘; ch=ch+‘a‘-‗A‘; /*statement A*/ ch=ch+‘A‘-‗a‘; /*statement B*/ What will be the value of ch after: 1. Statement A is executed? 2. Statement B is executed? Ver. 1.0 Slide 62 of 53
  63. 63. Programming in CPractice: 2.3 (Contd.) Solution: 1. ch is equal to s. Note that ‘a’-‘A’ gives 32 after statement 1 is executed. 2. ch is back to S after statement 2 is executed. Ver. 1.0 Slide 63 of 53
  64. 64. Programming in CBinary Operators (Contd.) There are some set or rules, if followed, would prevent unexpected results, at the time of execution of programs: Any operand of type char is converted to int. All floats are converted to doubles. If either operand is double, the other is converted to a double, giving a double result. Ver. 1.0 Slide 64 of 53
  65. 65. Programming in CPractice: 2.4 1. In which of the following assignments is there no loss of data? (i is an int, f a float, and d a double) i=d; d=f; f=d; i=f+d; d=i+f; 2. Is type casting necessary in the following example? int i,j; float f; double d; d=f+(float) i + j; Ver. 1.0 Slide 65 of 53
  66. 66. Programming in CPractice: 2.4 (Contd.) Solution: 1. a. Loss of data. int set equal to a double. b. No loss of data. double set equal to a float. c. Loss of data. float set equal to a double. d. Loss of data. Right-hand result is a double while left-hand side is just an int. e. No loss of data. Right-hand result is a double and left-hand side is also a double. 2. Not necessary. The ints will automatically be converted to doubles (following the conversion of the float to a double). Ver. 1.0 Slide 66 of 53
  67. 67. Programming in CTernary Operator Ternary Operator: Is a shorthand method for writing if.else conditional construct. Helps in reducing lines of code. Has the following form for the expression using the ternary operator: (test-expression) ? T-expression : F-expression; Ver. 1.0 Slide 67 of 53
  68. 68. Programming in CTernary Operator (Contd.) Consider the following example: if(condition) { Statements if condition is true } else { Statements if condition is false } Can be rewritten using the shorthand operator as follows: larger_of_the_two = ( x > y ) ? x : y; Ver. 1.0 Slide 68 of 53
  69. 69. Programming in CPractice: 2.5 1. State whether True or False: In the general form of an expression that uses a ternary operator, the test expression will be checked. If it is true, the T- expression will be evaluated, otherwise the F-expression will be evaluated. 2. What will the following statement do? quotient = (b==0) ? 0 : (a/b); /*a, b, and quotient are ints*/ 3. Can the preceding statement be written as follows? quotient = (b) ? (a/b) : 0; 4. What will the following statement do? always_negative = (j>0) ? j : (-j); Ver. 1.0 Slide 69 of 53
  70. 70. Programming in CPractice: 2.5 (Contd.) Solution: 1. True. 2. If b is non-zero, it will determine the quotient of a and b. If b equals zero, quotient is set to 0. 3. Yes. Note that if b is non-zero, the test expression (b) evaluates to true and hence quotient is set to (a/b). 4. The variable always_negative will always take on a non- negative value, i.e. it will be assigned the absolute value of j. The name of the variable always_negative is just a red herring. Remember that self-documenting variable names will help in writing programs that are readable. Note the unary operator (-j). Ver. 1.0 Slide 70 of 53
  71. 71. Programming in CCompound Assignment Operators Compound Assignment Operators: Are useful especially when long variable names are used. Has the following general form: left-value op= right-expression; Here op can be either + (add), - (subtract, * (multiply), / (divide), and % (modulo). Consider the following example: a_very_long_identifier=a_very_long_identifier + 2; It can be written as: a_very_long_identifier += 2; Ver. 1.0 Slide 71 of 53
  72. 72. Programming in CIncrement / Decrement Operators Increment / Decrement Operators: Are used to increase or decrease the value of a variable by 1. Has the following two forms: The ++ (two plus symbols without a space), called the increment operator while that in ++ before the variable is called the pre increment operator and after the variable is called the post increment operator. The -- (two minus symbols without a space), called the decrement operator while that in ++ before the variable is called the pre decrement operator and after the variable is called the post increment operator. Ver. 1.0 Slide 72 of 53
  73. 73. Programming in CIncrement / Decrement Operators (Contd.) Consider the following code snippet: total = sum++; /* statement A */ total = ++sum; /* statement B */ The first statement is equivalent to: total = sum; sum = sum + 1; While the second is the same as: sum = sum + 1; total = sum; Ver. 1.0 Slide 73 of 53
  74. 74. Programming in CPractice: 2.6 1. Consider the following code snippet: int sum = 3, total = 5; total = sum++; total = ++sum; /*statement A */ total = sum— total = --sum; /*statement B */ What will be the values of total and sum after: a. statement A is executed? b. statement B is executed? Ver. 1.0 Slide 74 of 53
  75. 75. Programming in CPractice: 2.6 (Contd.) 2. State whether True or False: The following statement: for(i = 0; i< 100); i = i + 1) { Some statements } can be written as: for (i = 0; i < 100; i++) { Some statements } Ver. 1.0 Slide 75 of 53
  76. 76. Programming in CPractice: 2.6 (Contd.) 3. State whether True or False: The for statement in #2 can also be written as: fori = 0; i < 100; ++i)/*Note: ++i and not i++*/ { Some statements } 4. Write a program, which reads in a year and reports on whether it is a leap year or not (centuries should also be considered). Ver. 1.0 Slide 76 of 53
  77. 77. Programming in CPractice: 2.6 (Contd.) Solution: 1. total=5, sum=5 total=3, sum=3 quite a complicated way of reducing total by 2. 2. True. i+1 is equivalent to i++. 3. True. i+1 is equivalent to 1+i. 4. Ver. 1.0 Slide 77 of 53
  78. 78. Programming in CUsing Loops The while and do…while looping constructs are generally used in situations where the number of execution of the loop is not known. The for loop construct is used when the number of execution of the loop is known. Ver. 1.0 Slide 78 of 53
  79. 79. Programming in CThe for Loop Construct The for loop construct: Has three components in the loop control: Initialization Condition Re-initialization (increment/decrement) Has the following sequence of execution: Initialization Evaluation of loop condition Body of loop Re-initialization Ver. 1.0 Slide 79 of 53
  80. 80. Programming in CThe for Loop Construct (Contd.) The sequence of execution of a complete for loop construct is shown in the following figure. INITIALIZATION FALSE EVALUATE CONDITION TRUE BODY OF LOOP REINITIALIZATION Ver. 1.0 Slide 80 of 53
  81. 81. Programming in CThe for Loop Construct (Contd.) In a for loop construct: Multiple initializations and/or multiple re- initializations, are separated by commas. Multiple conditions are specified using logical operators. Ver. 1.0 Slide 81 of 53
  82. 82. Programming in CPractice: 2.7 1. Write a function to accept twenty characters from the character set, and to display whether the number of lower- case characters is greater than, less than, or equal to number of upper-case characters. Display an error message if the input is not an alphabet. 2. Modify the function to accept characters endlessly until the character ! is input from keyboard. Ver. 1.0 Slide 82 of 53
  83. 83. Programming in CPractice: 2.7 (Contd.) Solution: 1. 2. Ver. 1.0 Slide 83 of 53
  84. 84. Programming in CControlling the Loop Execution At times there is a need to exit from a loop before the loop condition is re-evaluated after iteration. To exit from loop control, break and continue statements are used. Ver. 1.0 Slide 84 of 53
  85. 85. Programming in CPractice: 2.8 Write a function, which accepts numbers until 0 is entered or 10 numbers have been accepted. The function prints the total number of entries, the number of positive entries, and the sum of all the positive numbers. Ver. 1.0 Slide 85 of 53
  86. 86. Programming in CPractice: 2.8 (Contd.) Solution: Ver. 1.0 Slide 86 of 53
  87. 87. Programming in CUsing Formatted Input-Output Functions C provides the following functions for formatted input-output: printf() scanf() Ver. 1.0 Slide 87 of 53
  88. 88. Programming in CFormatted Output Syntax of the formatted output function printf() is: printf (format, data1, data 2, ….); Consider the following example: printf(―%c‖, inp); The character specified after % is called a conversion character. The conversion character allows one data type to be converted to another type and printed. Ver. 1.0 Slide 88 of 53
  89. 89. Programming in CFormatted Output (Contd.) The conversion characters and their meanings are shown in the following table. Character Meaning d the data is converted to decimal (integer) c the data is taken as a character s the data is a string and characters from the string are printed until a NULL character is reached f the data is output as a double or float with a default precision to 6 Ver. 1.0 Slide 89 of 53
  90. 90. Programming in CPractice: 2.9 What is the output of the statement: printf(―Integer is: %d; Alphabet is: %cn‖, inum, inp); where inum contains 15 and inp contains Z. Ver. 1.0 Slide 90 of 53
  91. 91. Programming in CPractice: 2.9 (Contd.) Solution: Integer is: 15; Alphabet is Z. Ver. 1.0 Slide 91 of 53
  92. 92. Programming in CFormatted Input The scanf() function is used for formatted input. The syntax for the scanf() functions is as follows: scanf (format, data1, data2……); Here format - The format-specification string data1, data2 - Data names where the input data is to be stored as per the format-specification string Ver. 1.0 Slide 92 of 53
  93. 93. Programming in CFormatted Input (Contd.) The format-specification string in scanf() consists of: Blanks, tabs, (also called white space characters). New line which are ignored. Conversion consisting of %, an optional number specification specifying the width and a conversion character. While accepting strings using scanf(), a space is considered as a string terminator. Ver. 1.0 Slide 93 of 53
  94. 94. Programming in CPractice: 2.10 Write a function to accept and display the element number and the weight of a Proton. The element number is an integer and weight is fractional. Ver. 1.0 Slide 94 of 53
  95. 95. Programming in CPractice: 2.10 (Contd.) Solution: #include<stdio.h> main() { int e_num; float e_wt; printf(―Enter the Element No. and Weight of a Protonn‖); scanf(―%d %f‖, &e_num, &e_wt); fflush(stdin); printf(―The Element No. is: ―, e_num); printf(―The weight of a Proton is: %fn―, e_wt); } Ver. 1.0 Slide 95 of 53
  96. 96. Programming in CPractice: 2.11 Write a function to input a string of continuous characters with no white space as part of the input. The function should assign the input to variables of the types specified in the following table. Position of character from Number of Type of argument to start of string characters assign 1 2 int 3 4 float 7 2 char (string) 9 3 int The function should also print out each of the assigned data items in separate lines. Ver. 1.0 Slide 96 of 53
  97. 97. Programming in CPractice: 2.11 Solution: #include<stdio.h> main() { int i,j; char str[3]; float fnum; printf(―Enter a string of 11 chrsn‖); /*why 11: because 11 is the total length of */ /*input.*/ scanf(―%2d %4f %2s %3d‖,&i, &fnum, str, &j); fflush(stdin); printf(―%2dn %4fn %2sn %3dn‖, i, fnum, str, j); } Ver. 1.0 Slide 97 of 53
  98. 98. Programming in CSummary In this session, you learned that: An operator is a symbol that is used to command the computer to do mathematical or logical manipulations. The operators in C language are classified into the following categories: Logical operators Unary operators Binary operators Ternary operator Compound assignment operators Increment/Decrement operators Ver. 1.0 Slide 98 of 53
  99. 99. Programming in CSummary (Contd.) The logical operators of C and their notations are as follows. Operator Notation OR || AND && NOT ! The unary operator prefixed to an integer constant or variable tells the compiler to reverse the sign by subtracting the value or variable from zero. Binary operators in C language are + (add), - (subtract), * (multiply), / (divide), and % (modulo). Ternary operator offers a shorthand way of writing the commonly used if…else construct. Ver. 1.0 Slide 99 of 53
  100. 100. Programming in CSummary (Contd.) The syntax for using the ternary operator is: (test-expression) ? T-expression : F-expression; Compound assignment operators simplify the statements. Increment / Decrement operators are used to increment/decrement a variable by 1. A for loop is used when the number of execution of the loop is known. The components of a for loop construct are: initialization loop condition reinitialization (increment/decrement) Ver. 1.0 Slide 100 of 53
  101. 101. Programming in CSummary (Contd.) The sequence of execution of a complete for loop is: initialization evaluation of the loop condition the body of the loop reinitialization The break and continue statements are used to exit from loop control. The break statement is used to exit from all loop constructs (while, do...while, and for) and switch...case statements. The continue statement is used to skip all subsequent instructions and brings the control back to the loop. The function printf() is used for formatted output to standard output based on a format specification. Ver. 1.0 Slide 101 of 53
  102. 102. Programming in CSummary (Contd.) The syntax of the function printf() is: printf(format, datal, data 2,,..); The function scanf() is used for formatted input from standard input and provides many of the conversion facilities of the function printf(). The syntax of the function scanf() is: scanf (format, datal, data2, ...); Ver. 1.0 Slide 102 of 53
  103. 103. Programming in CObjectives In this session, you will do the practice questions of Chapter 1 and Chapter 2. Ver. 1.0 Slide 103 of 53
  104. 104. Programming in CChapter 1 1. Write a function to accept a character and display it 40 times. 2. Write a function that accepts a number from 0 to 9, along with a string. The string should then be displayed the number of times specified. Ver. 1.0 Slide 104 of 53
  105. 105. Programming in CChapter 2 1. Write a for loop, which will produce the following output (Hint: use two nested for loops): 1 22 333 4444 55555 2. Create a C program, which calculates the triangular number of the user’s request, read from the keyboard using scanf(). A triangular number is the sum of the preceding numbers, so the triangular number 7 has the value of 7+6+5+4+3+2+1 (same as a factorial in mathematics, for example, factorial of 7 ---- !7). Ver. 1.0 Slide 105 of 53
  106. 106. Programming in CChapter 2 3. Create a C program to check whether the number entered by user is even or odd. Ver. 1.0 Slide 106 of 53
  107. 107. Programming in CObjectives In this session, you will learn to: Work with arrays Appreciate preprocessor directives Ver. 1.0 Slide 107 of 53
  108. 108. Programming in CWorking with Arrays Arrays: Are a group of similar objects. Can be defined as a contiguous area in memory. Can be referred to by a common name. Has a unique identifier for each element, called as a subscript or an index. Can be categorized as: One-dimensional/Single-dimensional arrays Multidimensional arrays Ver. 1.0 Slide 108 of 53
  109. 109. Programming in COne-Dimensional Arrays The syntax for declaring a one-dimensional array is: type arrayname[n]; For Example: char string [11]; Defines a character array named string to store 10 characters. string[0] to string[9] are for valid characters. string[10] for the string-terminator character, 0 (NULL). Similarly: int numbers [11]; Defines an integer type array called numbers to store 11 integers. Integers are stored in numbers[0] to numbers[10]. Ver. 1.0 Slide 109 of 53
  110. 110. Programming in CPractice: 3.1 1. Write the array definition statements for storing the following data: a. Ten amounts with paisa. b. Five ages to be stored in years and six non-fractional quantities. c. A thirty character long name. Ver. 1.0 Slide 110 of 53
  111. 111. Programming in CPractice: 3.1 (Contd.) Solution: a. float fnum[10]; b. int age[5], qty[6]; c. char name[31]; Ver. 1.0 Slide 111 of 53
  112. 112. Programming in COne-Dimensional Arrays (Contd.) Initializing Arrays: An array can be initialized, when declared. Initialization at the time of declaration is possible only outside a function unless it is declared static. Direct initialization is possible in the following ways: char strl[7]={‗E‘,‘X‘,‘O‘,‘D‘,‘U‘,‘S‘,‘0‘}; char str2[7]={"EXODUS"}; In the first case, individual elements have been moved into the array. Therefore, it is essential that the string terminator be specified explicitly. While in the second case, the string terminator gets attached automatically because a string has been assigned. Ver. 1.0 Slide 112 of 53
  113. 113. Programming in CPractice: 3.2 1. Write a function that stores the alphabets A to Z in an array by applying arithmetic on ASCII codes, given that the ASCII code of character A is 65. The function should display the string also. 2. In a file-delete utility program for 256 files the user response to whether a file is to be deleted or not is to be stored in an array as Y for yes and N for no for all files. By default the user response should be N for all files. Write a function that sets up an array and accepts user-responses. Ver. 1.0 Slide 113 of 53
  114. 114. Programming in CPractice: 3.2 (Contd.) Solution: Ver. 1.0 Slide 114 of 53
  115. 115. Programming in COne-Dimensional Arrays (Contd.) Array elements: Are referenced by using subscripts. Are integers, therefore array manipulation is possible through the use of variables. Ver. 1.0 Slide 115 of 53
  116. 116. Programming in CPractice: 3.3 1. Write a function to convert a character string into lower-case. 2. Write a function to compare two strings and to print the larger one. The strings may be compared in terms of ASCII code of each character in the strings. Ver. 1.0 Slide 116 of 53
  117. 117. Programming in CPractice: 3.3 (Contd.) Solution: Ver. 1.0 Slide 117 of 53
  118. 118. Programming in CPractice: 3.4 1. Write a function to accept up to 25 numbers and to display the highest and lowest numbers along with all the numbers. Ver. 1.0 Slide 118 of 53
  119. 119. Programming in CPractice: 3.4 (Contd.) Solution: Ver. 1.0 Slide 119 of 53
  120. 120. Programming in COne-Dimensional Arrays (Contd.) Array Addressing: To arrive at a particular element, the following formula is applied: Starting address + ( Offset number * Scaling factor) of the array Here, Scaling factor is the number of bytes of storage space required by the specific data type. Offset number * Scaling factor gives the number of bytes to be added to the starting address of the array to get to a desired element. Ver. 1.0 Slide 120 of 53
  121. 121. Programming in CPractice: 3.5 1. Write a program in C to extract a substring from a specified position containing a specified number of characters from an input string. Ver. 1.0 Slide 121 of 53
  122. 122. Programming in CPractice: 3.5 (Contd.) Solution: Ver. 1.0 Slide 122 of 53
  123. 123. Programming in CMultidimensional Arrays C also supports multidimensional arrays. A two-dimensional array is the simplest form of the multidimensional array. A two-dimensional array is an array of one-dimensional arrays. A two-dimensional array is also known as a two-d array. A two-d array is declared as follows: type arrayname[Row][Col]; Rules for initializing a two-d array are same as that of a one-dimensional array. The row subscript may be left blank for a more flexible declaration. Ver. 1.0 Slide 123 of 53
  124. 124. Programming in CPractice: 3.6 1. State whether True or False: If the number of salesmen is 5, then the declaration of the two-dimensional array and its initialization to zero would be: int s_p_array [5][4] = { {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, }; Ver. 1.0 Slide 124 of 53
  125. 125. Programming in CPractice: 3.6 (Contd.) Solution: 1. False. Note that since there are 5 salesman with 4 products, there should be 5 sets of {}, each containing four zeroes. The correct initialization is: int s_p_array [5][4] = { {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, }; Ver. 1.0 Slide 125 of 53
  126. 126. Programming in CMultidimensional Arrays (Contd.) Two-Dimensional Character Arrays: Are typically used to create an array of strings. Use two subscripts, one for row and the other for column. Are declared as: char err_msg [row] [col]; Can be initialized at the time of declaration. Ver. 1.0 Slide 126 of 53
  127. 127. Programming in CPractice: 3.7 1. Based on the books array, predict the output of the following commands: a. printf(―%c‖, books[2][5]); b. printf(―%s‖,books[3]); c. printf(―%d‖,books[4][7]); Ver. 1.0 Slide 127 of 53
  128. 128. Programming in CPractice: 3.7 (Contd.) Solution: a. M b. Birds, Beasts, and Relatives c. 97 Ver. 1.0 Slide 128 of 53
  129. 129. Programming in CPractice: 3.8 1. Write the program segment to calculate the class average across students in each subject. 2. Assume that the data exists in the arrays and averages have been calculated. Write program segments, which will allow the user to query on the arrays to: a. Display Student Names and Average Marks. b. Display Subjects and Class Averages. Ver. 1.0 Slide 129 of 53
  130. 130. Programming in CPractice: 3.8 (Contd.) c. Display Marks of a specific Student in a specific Subject. d. Display Subject wise marks of all students whose average is above 80. For each option the following action needs to be taken. OPTION ACTION a. Display each students name along with his average marks. b. Display each subject along with class average on the subject. c. Display list of students and list of subjects. Allow the user to choose one from each. Based on the numbers chosen, display the appropriate marks. Remember, subscripting in C starts from zero. d. Check the average of each student. Wherever average exceeds 80, display the student name and the subject name and marks in each subject. Ver. 1.0 Slide 130 of 53
  131. 131. Programming in CPractice: 3.8 (Contd.) Solution: Ver. 1.0 Slide 131 of 53
  132. 132. Programming in CAppreciating Preprocessor Directives Preprocessor directives: Are instructions to the compiler in the source code of a C program. Are not actually a part of the C language. Expand the scope of the C programming environment. Begin with a #. #include is also a preprocessor directive. #include instructs the compiler to include the specified source file into the one which contains the #include directive. #define defines an identifier and a string constant that will be substituted for the identifier each time it is encountered in the file. Ver. 1.0 Slide 132 of 53
  133. 133. Programming in CAppreciating Preprocessor Directives (Contd.) It helps in reducing the chances of inconsistency within the program and also makes the program easy to modify. Consider the following macro definition: #define TRUE 1 No semicolon is required after the statement. Every time the compiler encounters the string TRUE in the program, it substitutes it with the value 1. No text substitution will occur if the identifier is enclosed within quotes. Ver. 1.0 Slide 133 of 53
  134. 134. Programming in CSummary In this session, you learned that: An array can be defined as a contiguous area in memory, which can be referred to by a common name. In C, arrays can be categorized as: One-dimensional/Single-dimensional arrays Multidimensional arrays The syntax for declaring a one-dimensional array is as follows: type arrayname[n]; Array elements are referenced by using subscripts. The last element in a character array is reserved to store the string terminator character 0 (NULL). An array can be initialized, when declared, by specifying the values of some or all of its elements. Initialization can also be done inside the function, after the array has been declared, by accepting the values. Ver. 1.0 Slide 134 of 53
  135. 135. Programming in CSummary (Contd.) To arrive at the particular element, the following formula is applied: Starting address + ( Offset number * Scaling factor) of the array C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional (two-d) array. The general form of declaration of the two-d array would be: type arrayname[x][y]; Two-dimensional integer arrays are very much like one-dimensional integer arrays, the only difference being that two-dimensional arrays have two indices. Initialization of two-dimensional arrays can be done at the time of declaration itself. A better way to initialize a two-dimensional array is using the for statement. Ver. 1.0 Slide 135 of 53
  136. 136. Programming in CSummary (Contd.) Two-dimensional character arrays are declared in the same way as two-dimensional integer arrays: The first index specifies the number of strings. The second index specifies the length of the longest string plus one. Initialization can be done along with declaration, if done outside main(). Preprocessor directives are not actually a part of the C language; they expand the scope of the C programming environment. The preprocessor directives normally begin with a #. #include is also a preprocessor directive. It instructs the compiler to include the specified source file into the one which contains the #include directive. Ver. 1.0 Slide 136 of 53
  137. 137. Programming in CSummary (Contd.) The #define statement can be used to declare a variable with a constant value throughout the program. It helps in: Reducing the chances of inconsistency within the program. Making modification easier, as the value has to be changed only at one place. Ver. 1.0 Slide 137 of 53
  138. 138. Programming in CObjectives In this session, you will learn to: Declare and manipulate pointers Use pointers to manipulate character arrays Ver. 1.0 Slide 138 of 53
  139. 139. Programming in CDeclaring and Manipulating Pointers Every stored data item occupies one or more contiguous memory cells. Every cell in the memory has a unique address. Any reference to a variable, declared in memory, accesses the variable through the address of memory location. Pointers are variables, which contain the addresses of other variables (of any data type) in memory. Ver. 1.0 Slide 139 of 53
  140. 140. Programming in CDeclaring Pointers A pointer variable must be declared before use in a program. A pointer variable is declared preceded by an asterisk. The declaration: int *ptr; /* ptr is pointing to an int */ Indicates that ptr is a pointer to an integer variable. An uninitialized pointer may potentially point to any area of the memory and can cause a program to crash. A pointer can be initialized as follows: ptr= &x; In the preceding initialization, the pointer ptr is pointing to x. Ver. 1.0 Slide 140 of 53
  141. 141. Programming in CPractice: 4.1 1. In the following declaration: float *ptr_to_float; The pointer variable ptr_to_float is pointing to a variable of type ____________. 2. Is the following declaration valid? *ptr_to_something; 3. State whether True or False: An integer is declared In the following declaration: int *ptr_to_int; 4. Is the following declaration valid? int some_int, *ptr_to_int; Ver. 1.0 Slide 141 of 53
  142. 142. Programming in CPractice: 4.1 (Contd.) Solution: 1. float 2. No. When a pointer variable is being declared, the type of variable to which it is pointing to (int, float, or char) should also be indicated. 3. False. A pointer to an integer is being declared and not an integer. 4. Yes. It is okay to club declaration of a certain type along with pointers to the same type. Ver. 1.0 Slide 142 of 53
  143. 143. Programming in CManipulating Pointers Pointers can be manipulated like variables. The unary operator * gives value of the variable a pointer is pointing to. The unary operator * is also termed as the indirection operator. The indirection operator can be used only on pointers. Ver. 1.0 Slide 143 of 53
  144. 144. Programming in CPractice: 4.2 1. The symbol _________ is used to obtain the address of a variable while the symbol__________ is used to obtain the value of the variable to which a pointer is pointing to. 2. With the following declarations: int x, y, *ptr; Which of the following are meaningful assignments? a. x = y; b. y=*ptr; c. x = ptr; d. x = &.ptr; e. ptr = &x; f. x = &y; Ver. 1.0 Slide 144 of 53
  145. 145. Programming in CPractice: 4.2 (Contd.) 3. Consider the following sequence of statements and complete the partially-filled table: int x, y, *ptrl, *ptr2; x = 65; y = 89; ptr1 = &x; /*ptrl points to x */ ptr2 = &y/; /* ptr2 points to y */ x = *ptr1; /* statement A*) ptr1 = ptr2: /* statement B */ x = *ptr1; /* statement C*/ After statement &x x &y y ptr1 ptr2 A 1006 1018 B C Ver. 1.0 Slide 145 of 53
  146. 146. Programming in CPractice: 4.2 (Contd.) 4. What is the output of the following sequence of statements: int x, y, temp,*ptrl, *ptr2; /* declare */ x = 23; y = 37; ptrl = &x;/* ptrl points to x */ ptr2 = &y;/* ptr2 points to y */ temp = *ptrl; *ptr1 = *ptr2; *ptr2 = temp; printf(―x is %d while y is %d‖, x, y); Ver. 1.0 Slide 146 of 53
  147. 147. Programming in CPractice: 4.2 (Contd.) Solution: Ver. 1.0 Slide 147 of 53
  148. 148. Programming in CPointer Arithmetic Pointer Arithmetic: Arithmetic operations can be performed on pointers. Therefore, it is essential to declare a pointer as pointing to a certain datatype so that when the pointer is incremented or decremented, it moves by the appropriate number of bytes. Consider the following statement: ptr++; It does not necessarily mean that ptr now points to the next memory location. The memory location it will point to will depend upon the datatype to which the pointer points. May be initialized when declared if done outside main(). Consider the following example: #include <stdio.h> char movie[]= ―Jurassic Park‖; main() { char *ptr; Ver. 1.0 Slide 148 of 53
  149. 149. Programming in CPointer Arithmetic (Contd.) Consider the following example: #include <stdio.h> char movie[]= ―Jurassic Park‖; main() { char *ptr; ptr=movie; printf(―%s‖, movie); /* output: Jurassic Park */ printf(―%s‖,ptr); /* output: Jurassic Park */ ptr++; printf(―%s‖,movie); /* output: Jurassic Park */ printf(―%s",prr); /* output: urassic Park */ ptr++; printf(―%s‖,movie); /* output; Jurassic Park */ printf(―%s‖,ptr); /* output: rassic Park */ /* Note that the incrementing of the pointer ptr does not in any way affect the pointer movie */ } Ver. 1.0 Slide 149 of 53
  150. 150. Programming in CPractice: 4.3 1. Consider the following code snippet: #include <stdio.h> int one_d[] = {l,2,3}; main(){ int *ptr; ptr = one_d; ptr +=3; /* statement A*/ printf(―%dn‖, *ptr); /*statement B */ } a. After statement A is executed, the new address of ptr will be ____ bytes more than the old address. b. State whether True or False: The statement B will print 3. Ver. 1.0 Slide 150 of 53
  151. 151. Programming in CPractice: 4.3 (Contd.) Solution: a. 12 ( Size of integer = 4*3) b. False. Note that ptr is now pointing past the one-d array. So, whatever is stored (junk or some value) at this address is printed out. Again, note the dangers of arbitrary assignments to pointer variables. Ver. 1.0 Slide 151 of 53
  152. 152. Programming in CUsing Pointers to Manipulate Character Arrays Array name contains the address of the first element of the array. A pointer is a variable, which can store the address of another variable. It can be said that an array name is a pointer. Therefore, a pointer can be used to manipulate an array. Ver. 1.0 Slide 152 of 53
  153. 153. Programming in COne-Dimensional Arrays and Pointers One-Dimensional Arrays and Pointers: Consider the following example: #include <stdio.h> char str[13]={―Jiggerypokry‖}; char strl[]={ ―Magic‖}; main() { char *ptr; printf(―We are playing around with %s", str); /* Output: We are playing around with Jiggerypokry*/ ptr=str ; /* ptr now points to whatever str is pointing to */ printf(―We are playing around with %s" ,ptr); /* Output: We are playing around with Jiggerypokry */ } Ver. 1.0 Slide 153 of 53
  154. 154. Programming in COne-Dimensional Arrays and Pointers (Contd.) In the preceding example the statement: ptr=str; Gives the impression that the two pointers are equal. However, there is a very subtle difference between str and ptr. str is a static pointer, which means that the address contained in str cannot be changed. While ptr is a dynamic pointer. The address in ptr can be changed. Ver. 1.0 Slide 154 of 53
  155. 155. Programming in CPractice: 4.4 1. Given the declaration: char some_string [10]; some_string points to _________. 2. State whether True or False: In the following declaration, the pointer err_msg contains a valid address: char *err_msg = ―Some error message‖; 3. State whether True or False: Consider the following declaration: char *err_msg = ―Some error message‖; It is more flexible than the following declaration: char err_msg[19]=‖Some error message‖; Ver. 1.0 Slide 155 of 53
  156. 156. Programming in CPractice: 4.4 (Contd.) Solution: 1. some_string [0] 2. True 3. True. Note that one does not have to count the size of the error message in the first declaration. Ver. 1.0 Slide 156 of 53
  157. 157. Programming in CTwo-Dimensional Arrays and Pointers Two-dimensional arrays can be used to manipulate multiple strings at a time. String manipulation can also be done by using the array of pointers, as shown in the following example: char *things[6]; /* declaring an array of 6 pointers to char */ things[0]=‖Raindrops on roses‖; things[1]=‖And Whiskers on kettles‖; things[2]=‖Bright copper kettles‖; things[3]=‖And warm woolen mittens‖; things[4]=‖Brown paper packages tied up with strings‖; things[5]=‖These are a few of my favorite things‖; Ver. 1.0 Slide 157 of 53
  158. 158. Programming in CTwo-Dimensional Arrays and Pointers (Contd.) The third line of the song can be printed by the following statement: printf(―%s‖, things[2]); /*Output: Bright copper kettles */ Ver. 1.0 Slide 158 of 53
  159. 159. Programming in CPractice: 4.5 1. State whether True or False: While declaring two-dimensional character arrays using pointers, yon do not have to go through the tedium of counting the number of characters in the longest string. 2. Given the following error messages: Alls well File not found No read permission for file Insufficient memory No write permission for file Write a program to print all the error messages on screen, using pointers to array. Ver. 1.0 Slide 159 of 53
  160. 160. Programming in CPractice: 4.5 (Contd.) Solution: 1. True. New strings can be typed straight away within the {}. As in: char *err_msg_msg[]= { ―Alls well‖, ―File not found‖, ―No read permission for file‖, ―Insufficient memory‖, ―No write permission for file‖ }; The number of strings will define the size of the array. Ver. 1.0 Slide 160 of 53
  161. 161. Programming in CPractice: 4.5 (Contd.) 2. The program is: # include<stdio.h> # define ERRORS 5 char *err_msg[]= { /*Note the missing index*/ ―Alls well‖, ―File not found‖, ―No read permission for file‖, ―Insufficient memory‖, ―No write permission for file‖ }; main() { int err_no; for ( err_no = 0; err_no < ERRORS; err_no++ ) { printf ( ―nError message %d is : %sn‖, err_no + 1, err_msg[err_no]); } } Ver. 1.0 Slide 161 of 53
  162. 162. Programming in CTwo-Dimensional Arrays and Pointers (Contd.) Consider the following two-d array declaration: int num[3][4]= { {3, 6, 9, 12}, {15, 25, 30, 35}, {66, 77, 88, 99} }; This statement actually declares an array of 3 pointers (constant) num[0], num[l], and num[2] each containing the address of the first element of three single-dimensional arrays. The name of the array, num, contains the address of the first element of the array of pointers (the address of num[0]). Here, *num is equal to num[0] because num[0] points to num[0][0]. *(*num) will give the value 3. *num is equal to num[0]. Ver. 1.0 Slide 162 of 53
  163. 163. Programming in CString-Handling Functions Using Pointers Pointers can be used to write string-handling functions. Consider the following examples: /* function to calculate length of a string*/ #include <stdio.h> main() { char *ptr, str[20]; int size=0; printf(―nEnter string:‖); gets(str); fflush(stdin); for(ptr=str ; *ptr != 0; ptr++) { size++; } printf(―String length is %d‖, size); } Ver. 1.0 Slide 163 of 53
  164. 164. Programming in CUsing Pointers to Manipulate Character Arrays (Contd.) /*function to check for a palindrome */ # include <stdio.h> main() { char str[50],*ptr,*lptr; printf(―nEnter string :‖); gets(str); fflush(stdin); for(lptr=str; *lptr !=‘0; lptr++); /*reach the string terminator */ lptr--; /*position on the last character */ for(ptr=str; ptr<=lptr; lptr--,ptr++) { if(*ptr != *lptr) break;} if(ptr>lptr) printf(―%s is a palindrome‖ ); else printf(―%s is not a palindrome"); } Ver. 1.0 Slide 164 of 53
  165. 165. Programming in CSummary In this session, you learned that: A pointer is a variable, which contains the address of some other variable in memory. A pointer may point to a variable of any data type. A pointer can point to any portion of the memory. A pointer variable is declared as: datatype *<pointer variable name> A pointer variable is initialized as: pointer variable name> = &<variable name to which the pointer will point to> The & returns the address of the variable. The * before a pointer name gives the value of the variable to which it is pointing. Ver. 1.0 Slide 165 of 53

×