Learn C

3,843 views
3,940 views

Published on

C Language Tutorial

Published in: Technology, Education
1 Comment
5 Likes
Statistics
Notes
No Downloads
Views
Total views
3,843
On SlideShare
0
From Embeds
0
Number of Embeds
1,929
Actions
Shares
0
Downloads
106
Comments
1
Likes
5
Embeds 0
No embeds

No notes for slide

Learn C

  1. 1. Programming in ‘C’ By : Sudesh Kantila
  2. 2. Syllabus <ul><li>Unit - III </li></ul><ul><li>Need of programming languages, Defining problems </li></ul><ul><li>Flowchart and algorithm development </li></ul><ul><li>Unit – IV </li></ul><ul><li>Data types, constants, variables, operators and expressions </li></ul><ul><li>Input and output statements, Conditional and control statements, Arrays </li></ul><ul><li>Unit – V </li></ul><ul><li>Structures and unions </li></ul><ul><li>Pointers </li></ul><ul><li>File handling </li></ul>
  3. 3. Unit - III <ul><li>Need of programming languages, Defining problems </li></ul><ul><li>Flowcharts and algorithm development </li></ul><ul><li>Pseudocode and program development </li></ul>
  4. 4. Need for Programming Language <ul><li>We have some problem. </li></ul><ul><li>We have to solve the problem. </li></ul><ul><li>We can solve the problem, but we don’t want to repeatedly solve the similar problems. </li></ul><ul><li>We want to use the computer to do this task for us whenever required. </li></ul><ul><li>We have to tell the computer, “How to solve the problem.” </li></ul>
  5. 5. What is Problem? <ul><li>A problem is an obstacle which makes it difficult to achieve a desired goal, objective or purpose. </li></ul><ul><li>It refers to a situation, condition, or issue that is yet unresolved. </li></ul><ul><li>In a broad sense, a problem exists when an individual becomes aware of a significant difference between what actually is and what is desired. </li></ul>
  6. 6. Problem Solving <ul><li>Every problem asks for an answer or solution. Trying to find a solution to a problem is known as problem solving. </li></ul><ul><li>Problem solving forms part of thinking. It occurs if an individual does not know how to proceed from a given state to a desired goal state. </li></ul>
  7. 7. Examples – Problem Solving <ul><li>Mathematical problem is a question about mathematical objects and structures that may require a distinct answer or explanation or proof. </li></ul><ul><li>In society, a problem can refer to particular social issues, which if solved would yield social benefits. </li></ul><ul><li>In this class, the problem is to learn C programming, which if solved will make you a good programmer. </li></ul>
  8. 8. How to solve a problem? <ul><li>If you have a problem, either you can solve it easily or not(difficult). </li></ul><ul><li>If the problem is easy enough, solve it else proceed to next step. </li></ul><ul><li>Divide the problem into smaller problems (sub-problems) and start from first to last. </li></ul><ul><li>Now, either you can solve this smaller problem easily or not (still difficult). </li></ul><ul><li>Goto step 2. </li></ul><ul><li>After completing this process, the entire big problem has been solved. </li></ul>
  9. 9. Algorithm – Logic to solve <ul><li>If you have solved the prolem, you have definitely used some procedure (logic) to do so. </li></ul><ul><li>There may be many different logic that can solve the problem. </li></ul><ul><li>You may write this logic into small steps (easy enough) in english (or whatever language you understand). </li></ul><ul><li>This block of steps to solve the problem is called an “Algorithm”. </li></ul>
  10. 10. A simple problem - Factorial <ul><li>We have to calculate the factorial of a number ‘N’. </li></ul><ul><li>We know how to calculate the factorial. </li></ul><ul><li>Logic 1: N! = N * N-1 * N-2 * …* N-(N-1) {N-(N-1)=1} </li></ul><ul><li>Logic 2: N! = 1 * 2 * 3 * … * N </li></ul><ul><li>Logic 3: N! = N * (N-1)! (Recursion) </li></ul>
  11. 11. Logic 1: (Algorithm) <ul><li>START </li></ul><ul><li>INPUT AN INTEGER – N </li></ul><ul><li>LET F=1 </li></ul><ul><li>IF N > 1 GOTO STEP 5 ELSE STEP 8 </li></ul><ul><li>F = F * N </li></ul><ul><li>N = N – 1 </li></ul><ul><li>GOTO STEP 4 </li></ul><ul><li>OUTPUT F </li></ul><ul><li>STOP </li></ul>
  12. 12. Logic 2: (Algorithm) <ul><li>START </li></ul><ul><li>INPUT AN INTEGER – N </li></ul><ul><li>LET F=1, X=1 </li></ul><ul><li>IF X < N GOTO STEP 5 ELSE STEP 8 </li></ul><ul><li>X = X + 1 </li></ul><ul><li>F = F * X </li></ul><ul><li>GOTO STEP 4 </li></ul><ul><li>OUTPUT F </li></ul><ul><li>STOP </li></ul>
  13. 13. Flow Chart – Graphical Algorithm <ul><li>Algorithms are written in some natural language, e.g. – English, हिन्दी , Chinease etc. </li></ul><ul><li>There may be some problem to understand the algorithm if a person from different region speaking a different language needs to know the logic. </li></ul><ul><li>To overcome this problem, logic may be represented in a graphical way. </li></ul><ul><li>This graphical representation of algorithm is called ‘Flow Chart’ </li></ul>
  14. 14. Flow Chart – Logic 1 Yes No LET F=1 IF N > 1 INPUT N START OUTPUT F START F = F * N N = N - 1
  15. 15. Flow Chart – Logic 2 No Yes LET F=1 X = 1 IF X < N INPUT N START OUTPUT F START X = X + 1 F = F * X
  16. 16. Common Flow Chart Shapes <ul><li>Flow Lines </li></ul><ul><li>Terminator </li></ul><ul><li>Input / Output Box </li></ul><ul><li>Process </li></ul><ul><li>Decision Box </li></ul><ul><li>(On Page and Off Page) Connectors </li></ul><ul><li>Predefined Process </li></ul>
  17. 17. Pseudocode <ul><li>Pseudocode is a kind of structured english for describing algorithms. </li></ul><ul><li>It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax.  </li></ul><ul><li>At the same time, the pseudocode needs to be complete. It describe the entire logic of the algorithm so that implementation becomes a rote mechanical task of translating line by line into source code (coding). </li></ul><ul><li>Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules. </li></ul>
  18. 18. Pseudocode – Logic 1 <ul><li>GET value of N </li></ul><ul><li>SET initial value of F to 1 </li></ul><ul><li>WHILE N > 1 </li></ul><ul><li>F = F * N N = N – 1 </li></ul><ul><li>ENDWHILE </li></ul><ul><li>DISPLAY value of F </li></ul>
  19. 19. Programming (Coding) in C <ul><li>main() </li></ul><ul><li>{ </li></ul><ul><li>int n; long f = 1 ; printf(“ Input n to get factorial : ”); scanf(“ %i ”, & n); while (n > 1) { f = f * n; n = n – 1 ; } printf(“ Factorial of %i is %li ”,n,f); </li></ul><ul><li>retrun 0 ; </li></ul><ul><li>} </li></ul>
  20. 20. Unit - IV <ul><li>Structure of a ‘C’ program, preprocessor, main function and return statement, Tokens, Identifiers and Keywords </li></ul><ul><li>Data Types, Constants, Variables, Operators and Expressions </li></ul><ul><li>Input and output statements, Conditional and control statements, Arrays </li></ul>
  21. 21. Basic Structure of a ‘C’ Program <ul><li>Documentation Section </li></ul><ul><li>Link Section </li></ul><ul><li>Definition Section </li></ul><ul><li>Global Declaration Section </li></ul><ul><li>main( ) Function Section </li></ul><ul><li>{ </li></ul><ul><li>Local Declaration Part </li></ul><ul><li>Executable Part </li></ul><ul><li>} </li></ul><ul><li>Sub function Section </li></ul><ul><li>Function 1 ( ) </li></ul><ul><li>Function 2 ( ) </li></ul><ul><li>. </li></ul><ul><li>Function N ( ) </li></ul>
  22. 22. C Program – Logic 3 <ul><li>/* Program to calculate the factorial of a given integer - N */ </li></ul><ul><li>/* Link Section */ </li></ul><ul><li>#include <stdio.h> </li></ul><ul><li>/* Definition Section */ </li></ul><ul><li>#define N 5 </li></ul><ul><li>/* Global Declaration Section / </li></ul><ul><li>long f = 1 ; </li></ul><ul><li>/* main() Function Section */ </li></ul><ul><li>main() </li></ul><ul><li>{ </li></ul><ul><li> /* Local Declaration Part */ </li></ul><ul><li>int n = N; </li></ul><ul><li>long int factorial (int); </li></ul><ul><li> /* Executable Part */ </li></ul><ul><li>f = factorial (n); </li></ul><ul><li>printf(“ Factorial of %i is %li ”,N,f); </li></ul><ul><li> /* Return Part */ </li></ul><ul><li>return 0; </li></ul><ul><li>} </li></ul>
  23. 23. C Program – Logic 3 <ul><li>/* Function to calculate factorial - Recursive*/ </li></ul><ul><li>/* Sub function Section */ </li></ul><ul><li>long int factorial(int x) </li></ul><ul><li>{ </li></ul><ul><li>/* Local Declaration Part */ </li></ul><ul><li>long f = 1 ; </li></ul><ul><li>/* Executable Part */ </li></ul><ul><li>if ( x > 1 ) </li></ul><ul><li>f = x * factorial ( x - 1 ); </li></ul><ul><li>/* Return Part */ </li></ul><ul><li>return f; </li></ul><ul><li>} </li></ul>
  24. 24. Preprocessor <ul><li>All lines in ‘C’ or ‘C++”, that begin with # (hash) are meant for preprocessor. </li></ul><ul><li>These are called preprocessor directives . </li></ul><ul><li>These are processed by preprocessor before the program is given to compilor. </li></ul><ul><li>E.g. – #include <stdio.h> instructs the preprocessor to copy the content of the file ‘stdio.h’ #define N 5 Instructs the preprocessor to substitute the token N with 5 in the entire program code before compilation </li></ul>
  25. 25. main( ) function <ul><li>A ‘C’ program is a group of functions. </li></ul><ul><li>In this group, one of the functions is the main() function. </li></ul><ul><li>This is the function, where the execution begins. </li></ul><ul><li>It calls other functions to perform sub-tasks. </li></ul><ul><li>Every function, including main must be defined before use. </li></ul><ul><li>Function names are always followed by () a pair of paranthesis (may or may not be empty). </li></ul><ul><li>Functions may be declared (protype), defined (Implementation) or called (use). E.g. – long factorial( int ); /* Prototype declaration*/ long factorial( int n) { </li></ul><ul><ul><li>… … </li></ul></ul><ul><ul><li>} /* Defination or Implementation*/ </li></ul></ul><ul><ul><li>f = factorial( 5 ); /* Call or use */ </li></ul></ul>
  26. 26. return statement <ul><li>return is a keyword and the statement having this key word is called return statement. </li></ul><ul><li>This is usually the last statement in a function. </li></ul><ul><li>There may be more than one return statements in a single function. </li></ul><ul><li>It returns back the control (CPU) to calling party (function or Operating System). </li></ul><ul><li>It may bring back a value of the type the function is declared. E.g. – long factorial( int n) ; will return a long value (while it takes an int argument). </li></ul><ul><li>This is the value returned by the function. </li></ul><ul><li>This value may be used by the calling party to get the result of a calculation or to know the status of task. E.g. - f = factorial( 5 ); </li></ul><ul><li>A function declared as void does not returns a value. </li></ul>
  27. 27. Token <ul><li>Individual words and punctuation marks are called Tokens. </li></ul><ul><li>In a C program the smallest individual units are know as Toens. </li></ul><ul><li>C has six types of Tokens. </li></ul><ul><li>Keywords </li></ul><ul><li>Constants </li></ul><ul><li>Identifiers </li></ul><ul><li>Strings </li></ul><ul><li>Operators </li></ul><ul><li>Special Symbols </li></ul>
  28. 28. Keywords <ul><li>There are only 32 keywords in ‘C’ </li></ul><ul><li>All keywords have a fixed meanings and these meaning can not be changed. </li></ul><ul><li>Kewords serve as basic building blocks for program statemnts </li></ul><ul><li>All keywords must be written in lowercase. auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while </li></ul>
  29. 29. Constants <ul><li>Fixed Value e.g. : 12.3, 25, ‘A’, π </li></ul><ul><li>Itentifiers having fixed values </li></ul><ul><li>SYMBOLIC CONSTANTS </li></ul><ul><ul><li>#define IDENTIFIER Value </li></ul></ul><ul><ul><li>e.g. - #define PI 3.14 </li></ul></ul><ul><li>CONSTANT VARIABLES </li></ul><ul><ul><li>const data-type Itentifier = Value; </li></ul></ul><ul><ul><li>e.g. – const float Pi = 3.14 ; </li></ul></ul>
  30. 30. Identifiers <ul><li>Itentifiers refer to the name of variables, functions, and arrays. </li></ul><ul><li>These are user-defined names. </li></ul><ul><li>Consists of a sequence of letters, _ (underscore) and digits. </li></ul><ul><li>First character may be either a letter or a _ (underscore) character only. </li></ul><ul><li>Both UPPERCASE and lowercase letters are permitted but different. </li></ul><ul><li>Usually, lowercase letters are used for variable and function names and UPPERCASE letters for constant names. </li></ul><ul><li>E.g. – number, num1, Pi, main, first_number, var20 etc. </li></ul>
  31. 31. Strings <ul><li>Any sequence enclosed in &quot; &quot; a pair of double quotation mark is called a string. </li></ul><ul><li>The sequence may have letters (a-z,A-Z, digits (0-9), special characters ($, #, @, *, + ), format speciefiers (%c), escape sequences( ) and white spaces( ). </li></ul><ul><li>Strings are stored in the array of characters in ‘C’. There is no specific data type to hold strings in ‘C’. </li></ul><ul><li>E.g. – “ Sobhasaria Engineering College ”, “ Number 1 = %d ”, “ 123 ”, “ A ” </li></ul>
  32. 32. Operators <ul><li>An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. </li></ul><ul><li>Operators are used in programs to manipulate data and variables. </li></ul><ul><li>They usually form a part of the mathematical of logical expresions. E.g. - + (addition), * (multiplication), % (modulus), = (assignment), == (equality), sizeof , & (address of), && (Logical AND) etc. </li></ul>
  33. 33. Expression <ul><li>Any statement or part thereof, using some operator (with operand(s)) to perform some task. </li></ul><ul><li>E.g. - sum = a + b a==b a && b a++ &sum sizeof(a) </li></ul>
  34. 34. Statements <ul><li>An instruction written for compilor to perform certain action. </li></ul><ul><li>Necessarily ends with a semicolon (;). </li></ul><ul><li>Multiple statements may be clubbed together to form a compound statement. </li></ul><ul><li>Simple statement area = Pi * radius * radius; printf(“ Area = %i ”,area); </li></ul><ul><li>Compound Statement { f = f * n; n = n - 1 ; } </li></ul>
  35. 35. Data Types <ul><li>Primary / Basic Data Types (Integral, Floating point) </li></ul><ul><li>User Defined Data Types typedef type identifier; enum identifier {value1, …, value n}; </li></ul><ul><li>Derived Data Types (Array, Structure, Union) </li></ul><ul><li>Empty Data Sets void </li></ul>
  36. 36. Basic Data Types
  37. 37. Other data types <ul><li>All other data types other than Basic will be discussed later in UNIT – 5. </li></ul>
  38. 38. Remember about Constants <ul><li>Their value does not change during the execution of a program </li></ul><ul><li>They can not appear on the left side of the assignment operators like =, +=, -=, *=, /=, %= etc. </li></ul><ul><li>Any variable declaration with const qualifier must assign value to the identifier. e.g. – const float Pi; /* invalid */ const double C = 3.0e+8 ; /* Valid */ </li></ul>
  39. 39. Variables <ul><li>An identifier that is allocated a memory location and can holds different values at different times. </li></ul><ul><li>Value may be changed at any time. </li></ul><ul><li>Needs to be declared before use. </li></ul><ul><li>Stores value of the specified data-type. </li></ul><ul><li>Example: - int x; float y, z; char ch = ‘ A ’; char name[ 50 ]; </li></ul>
  40. 40. Types of Variables
  41. 41. Automatic (default) variable <ul><li>All variables declared without any specifier or auto e.g. - int number = 1 ; auto float radius = 5.4 ; </li></ul><ul><li>Allocated in stack memory. </li></ul><ul><li>Have an address, which may be get using & (address of) operator. e.g. - int * address = & number; scanf(“ %f ”, & radius); </li></ul><ul><li>Value of a local auto variable is lost when a function returns and cannot be accessed in subsequent calls to the same function also. </li></ul>
  42. 42. Static variable <ul><li>All variables declared with static specifier e.g. - static number = 1 ; static float radius = 5.4 ; </li></ul><ul><li>Allocated in heap memory. </li></ul><ul><li>Have an address (different from stack) , which may be get using & (address of) operator. e.g. - int * address = & number; scanf(“ %f ”, & radius); </li></ul><ul><li>Value of a local static variable does not lost when a function returns and can be used in subsequent calls to the same function. </li></ul>
  43. 43. Register variable <ul><li>All variables declared with register specifier e.g. - register number = 1 ; register float radius = 5.4 ; </li></ul><ul><li>Allocated in CPU Registers and hence fastest in access. </li></ul><ul><li>Do not have an address. scanf(“ %f ”, & radius); /* Invalid */ </li></ul><ul><li>Value to register variables may be assigned only using assignment operators, like: =, +=, -=, *=, /=, %= </li></ul>
  44. 44. Extern variable <ul><li>All variables declared with extern specifier in public variable declaration section, e.g. - extern int number; extern float radius; </li></ul><ul><li>Indicates that the variable is already declared externally i.e. in global space in another file. </li></ul><ul><li>Public in scope and needs to be declared somewhere else also without this specifier. </li></ul><ul><li>Allocated in Heap and shared among many functions declared in different files. </li></ul><ul><li>Have an address which may be get using & (address of) operator. e.g. - int * address = & number; scanf(“ %f ”, & radius); </li></ul>
  45. 45. Operators <ul><li>Assignment Operators </li></ul><ul><li>Arithmatic Operators </li></ul><ul><li>Increment and Decrement Operators </li></ul><ul><li>Relational Operators </li></ul><ul><li>Logical Operators </li></ul><ul><li>Conditional Operator </li></ul><ul><li>Bitwise Operators </li></ul><ul><li>Other Operators </li></ul>
  46. 46. Assignment Operators (=) <ul><li>Assigns value of expression on the right to the variable on the left. e.g. – area = PI * radius * radius; i = 2 ; float height = 5.406 ; f = f * number; </li></ul><ul><li>When assignment expression is of the type: - variableX = variableX (arithmatic op) expression; </li></ul><ul><li>It may also be written as: - variableX (arithmatic op) = expression; e.g. – f = f * number; f *= number; </li></ul><ul><li>This type of notation is also called Short hand operator, i.e.: +=, -=, *=, /= and %=. </li></ul>
  47. 47. Arithmatic Operators ( +,-,*,/,% ) <ul><li>Perform basic arithmatics like addition, substration, multiplication, division and modulo division (Integer only). e.g. – y = m * x + c; </li></ul><ul><li>Two levels of precedence – Higher Precedence ( * , / , %) Lower Precedence ( +, -) </li></ul><ul><li>Precedence can be exclusively defined using paranthesis ( ), which have Highest Precedence. E.g.: - dy = y – (m * (x + dx)) + c; </li></ul><ul><li>No operator for Power unlike many other languages. </li></ul>
  48. 48. Increment (++) and Decrement (--) Operators <ul><li>Unary Operators </li></ul><ul><li>Increment operator increases the value of the operand. e.g. – int i = 2 ; /* Initial value of i is 2 */ i ++ ; /* New value of i is 3 */ </li></ul><ul><li>Decrement operator decreases the value of the operand. e.g. – int i = 2 ; /* Initial value of i is 2 */ i -- ; /* New value of i is 1 */ </li></ul>
  49. 49. Pre and Post <ul><li>Increment and decrement operators may be used in Pre or Post form. e.g. – ++ i; /* Pre-Increment */ i -- ; /* Post-Decrement */ </li></ul><ul><li>When these operators are used with stand alone operands, there is no change in the result using Pre or Post form. e.g. - i = 2; i ++ ; /* New value of i is 3 */ i = 2; ++ i; /* New value of i is 3 */ </li></ul><ul><li>When used as a part of expression, Pre form increases or decreases the value before use in expression (Higher priority than other operators) but Post form increases or decreases the value after use in expression (Lower priority than other operators). e.g. - i = 2; j = i ++ ; /* i = 3, j = 2 */ i = 2; j = ++i ; /* i = 3, j = 3 */ </li></ul>
  50. 50. Relational Operators <ul><li>These operators usually return true or false, depending on whether the conditional relationship between the two operands holds or not. </li></ul><ul><li>An expression created using a relational operator forms what is known as a relational expression or a condition. </li></ul><ul><li>Relational expressions are used in decision statements such as if and while to decide the course of action of a running program. </li></ul>
  51. 51. Relational Operators <ul><li>There are six relational operators in ‘C’. </li></ul><ul><ul><li>Equal to == </li></ul></ul><ul><ul><li>Not equal to != </li></ul></ul><ul><ul><li>Greater than > </li></ul></ul><ul><ul><li>Greater than or equal to >= </li></ul></ul><ul><ul><li>Less than < </li></ul></ul><ul><ul><li>Less than or equal to <= </li></ul></ul><ul><li>E.g. – if (a == b) while (N > 1 ) </li></ul>
  52. 52. Logical Operators <ul><li>There are only three logical operators. </li></ul><ul><li>Works or logical operands and return logical result. </li></ul><ul><ul><li>Logical AND && </li></ul></ul><ul><ul><li>Logical OR || </li></ul></ul><ul><ul><li>Logical NOT ! </li></ul></ul><ul><li>Logical operators are used when we want to test more than one conditions and make decision. </li></ul><ul><li>Logical AND ( && ) and Logical OR ( || ) works on two operands while Logical NOT ( ! ) works on a single operand and complements its value. </li></ul>
  53. 53. Logical Operators (Truth Table) Operand 1 Operator Operand 2 Result False (0) && False (0) False (0) False (0) && True (1) False (0) True (1) && False (0) False (0) True (1) && True (1) True (1) False (0) || False (0) False (0) False (0) || True (1) True (1) True (1) || False (0) True (1) True (1) || True (1) True (1) False (0) ! Not Applicable True (1) True (1) ! False (0)
  54. 54. Logical Operators (Example) <ul><li>if ((a > b) && (a > c)) max = a; else if ((a > b) && (a <= c)) max = c; else if ((a <= b) && (b < c)) max = c; else max = b; </li></ul>
  55. 55. Conditional Operator (?:) <ul><li>Only ternary operator that works on three operands. </li></ul><ul><li>May be used to decide like if else construct. </li></ul><ul><li>Syntex: (exp1)?exp2:exp3; e.g. – (N >= 0) ? &quot;N is positive&quot; : &quot;N is negative&quot;; abs = (n < 0) ? (-1 * n) : n; </li></ul>
  56. 56. Bitwise Operators ( << , >> ) <ul><li>Operators that works on BI nary digi TS (BITS) instead on bytes, words, dword or qword. </li></ul><ul><li>Two types – Shift Operators & Logical Operators, </li></ul><ul><li>Bitwise shift operators shifts the BITS by specified no. of places in left or right direction. e.g. – int a = 99 ,b,c; /* a = 00000000011000 11 */ b = a >> 2; /* b= 00 00000000011000 */ c = b << 1 + a << 1 ; 0000000000011000 << 1 = 0000000000110000 0000000001100011 << 1 = 0000000011000110 + ---------------- c = 0000000011110110 </li></ul><ul><li>In decimal notation, these values are : a = 99 b = 24 c = 246 </li></ul>
  57. 57. Bitwise Operators ( & , | , ! ) <ul><li>Bitwise logical operators are similar to logical operators ( && , || and ! ) with the only difference that these works on individual BITS. </li></ul><ul><li>Example: - int a = 25, b = 99, c,d,e; c = a & b; /* c = 1 */ d = a | b; /* d = 123 */ e = ! a; /* e = 220 */ </li></ul><ul><li>Explaination 00011001 00011001 00011001 01100011 01100011 </li></ul><ul><li>& -------- | -------- ! -------- 00000001 01111011 11100110 </li></ul>
  58. 58. Other operators <ul><li>sizeof : works on single operand (data-type, variable or constant) and return the memory size (in bytes) occupied by the operand. E.g. – sizeof (char), sizeof (number) </li></ul><ul><li>& (address of) : works on single memory variable and return its address in memory. E.g. – int * pn = & number; scanf(“%i”, & number); </li></ul>
  59. 59. Other operators <ul><li>Member operators: Dot( . ) operator is used to access the member of a of struct or union type variable using variable name. </li></ul><ul><li>Arrow ( -> ) operator is used to access the member of a struct or union type variable using pointer to variable . </li></ul><ul><li>Example: - struct subject { int min; int max; } math; struct subject * pm = & math; math . min = 0 ; math . max = 100 ; pm -> min = 0 ; pm -> max = 100 ; </li></ul>
  60. 60. Other operators <ul><li>Comma ( , ) Operator: It can be used to link the related expressions together. A comma linked list of expressions is evaluated left to right and the value of right-most expression is the value of the combined expression. E.g . - value = (x = 5 ,y = 10 ,x + y); /* 15 */ </li></ul><ul><li>It is also used to declare more than one variables with a single data-type. E.g. – int x, y, z; /*Declares x,y,z as int*/ </li></ul><ul><li>It is also used to separate arguments in a argument list passed to a function. E.g. – printf (“%i + %i = %i ”,a,b,c); /*Passes four arguments to printf() */ </li></ul>
  61. 61. Input & Output Statements <ul><li>Input statements read some data from files or keyboard. </li></ul><ul><li>Output statements write output to the file, monitor or printer. </li></ul><ul><li>No inbuild support for such statement was provided by ‘C’, i.e. no keyword is capable of I/O. </li></ul><ul><li>This functionality has been appended later using additional librarie, which may be linked by including the STandarD Input Output Header file <stdio.h>. </li></ul><ul><li>In Borland C/C++ compilor, one more library is provided for DOS based CONsole Input Output operations that may be linked by including Header file <conio.h>. </li></ul><ul><li>“ conio.h” is not a standard library and hence not neccessarily available on Microsoft or GNU C/C++ distributions. </li></ul><ul><li>Most of the IDE like Borland’s Turbo C++ 3.0/4.5 or GNU based Dev C++ 4/5 includes standard i/o library even if we do not include stdio.h header file. </li></ul>
  62. 62. Input & Output Statements I/O statements are written using I/O functions.
  63. 63. Unformatted Input – getc() <ul><li>It just reads character data from specified file or Keyboard. </li></ul><ul><li>No control on the format of the data. </li></ul><ul><li>Interface: int getc( FILE * ) </li></ul><ul><li>Explaination: getc() function takes an argument of the FILE pointer type. To read the data from keyboard, give stdin as argument. e.g. – char ch; ch = getc(stdin); </li></ul><ul><li>This is implemented as MACRO. The function equivalent is fgetc(). </li></ul>
  64. 64. Unformatted Input – getchar() <ul><li>It just reads data from Keyboard. </li></ul><ul><li>No control on the format of the data. </li></ul><ul><li>Interface: int getchar( void ) </li></ul><ul><li>Explaination: getchar() function takes no argument. It reads the data from keyboard only. e.g. – char ch; ch = getchar(); </li></ul><ul><li>It is implement as MACRO. It reads the data after pressing <RETURN> key. </li></ul><ul><li>fgetchar() is its function implementation. </li></ul>
  65. 65. Unformatted Input – getch() <ul><li>Just another function like getchar(). </li></ul><ul><li>No control on the format of the data. </li></ul><ul><li>Interface: int getch( void ) </li></ul><ul><li>Explaination: getch() function takes no argument. It reads the data from K/B only. e.g. – char ch; ch = getch(); </li></ul><ul><li>It reads the data as the key is pressed, without the need of <RETURN> key. The key pressed is not displayed on the screen </li></ul>
  66. 66. Unformatted Input – getche() <ul><li>Similar to getch() in all respects expect that the key pressed is displayed on the screen. </li></ul><ul><li>Interface: int getche( void ) </li></ul><ul><li>E.g. – char ch; ch = getche(); </li></ul><ul><li>getch() & getche() are also used to pause the program for a key to press, for the purpose to view the output. </li></ul>
  67. 67. Unformatted Input – getw() <ul><li>Similar to getc () in all respects expect that the it reads an integer value instead of a character. </li></ul><ul><li>Interface: int getw( FILE * ) </li></ul><ul><li>E.g. – int num; num = getw(stdin); </li></ul><ul><li>getw() function is a non-ANSI function and a similar function getwc() is used to read w_char used to store unicode character. </li></ul>
  68. 68. Unformatted Input – fgets() <ul><li>It reads string data (including white space) from specified file or K/B and used to do so usually. </li></ul><ul><li>Interface: char * fgets( char * , int , FILE * ) </li></ul><ul><li>Explaination: fgets() function reads a string of the length specified by the 2rd argument from the file specified by the 3 rd argument and stores it in the variable specified by 1 st argument and append a (NULL) ''. It also return a pointer to the string stored. e.g. – char name[ 20 ]; fgets(name, 19 ,stdin); </li></ul>
  69. 69. Unformatted Input –gets() <ul><li>It just reads string data from Keyboard. </li></ul><ul><li>Interface: char * gets( char * ) </li></ul><ul><li>Explaination: fgets() function reads a string and stores it in the variable specified by argument and appends a (NULL) '' character in the last. It also return a pointer to the string stored. e.g. – char name[ 20 ]; gets(name); </li></ul><ul><li>gets() function has less control over the string read and is dangerous. It must be avoided. Use fgets() or scanf() function instead. </li></ul>
  70. 70. Formatted Input – fscanf() <ul><li>Using fscanf(), we can read data from any file pointed by a FILE * or K/B. </li></ul><ul><li>Interface: int fscanf( FILE * , const char * ,...) </li></ul><ul><li>E.g. – char ch; int num; fscanf(stdin,&quot; %c%i &quot;, & ch, & num); </li></ul><ul><li>This is used specially in file handling. </li></ul><ul><li>It reads data from the stream specified by 1 st arg of the form specified by 2 nd arg and stores at the addresses specified by subsequent arguments. It also returns the number of data items read and stored successfully. </li></ul>
  71. 71. Formatted Input – scanf() <ul><li>Using scanf(), we can read data from the Keyboard. It is a restricted version of fscanf function limited to use stdin as first argument. </li></ul><ul><li>Interface: int scanf( const char * ,...) </li></ul><ul><li>E.g. – char ch; int num; scanf(&quot; %c%i &quot;, & ch, & num); </li></ul><ul><li>This is used specially to read data from K/B. </li></ul><ul><li>It reads data from the K/B of the form specified by 1 st arg and stores at the addresses specified by subsequent arguments. It also returns the number of data items read and stored successfully. </li></ul>
  72. 72. Formatted Input – sscanf() <ul><li>Using sscanf(), we can read or extract data from a string buffer. </li></ul><ul><li>Interface: int fscanf( const char * , const char * ,...) </li></ul><ul><li>E.g. – char ch; char * str = &quot;A1 is the best&quot;; int num; sscanf(str,&quot; %c%i &quot;, & ch, & num); /* Ch=‘A’, num=1 */ </li></ul><ul><li>It reads data from the string buffer specified by 1 st arg of the form specified by 2 nd arg and stores at the addresses specified by subsequent arguments. It also returns the number of data items read and stored successfully. </li></ul>
  73. 73. Unformatted Onput – putc() <ul><li>It just writes data to file/monitor/printer. </li></ul><ul><li>No control on the format of the data. </li></ul><ul><li>Interface: int putc( const char , FILE * ) </li></ul><ul><li>Explaination: putc() function takes two argument of the FILE pointer and char types. To write the data to monitor, give stdout or stderr as first argument. e.g. – char ch='F'; putc(stdout,ch); </li></ul><ul><li>This is implemented as MACRO. The function equivalent is fputc(). </li></ul>
  74. 74. Unformatted Output – putchar() <ul><li>It just writes data to the monitor. </li></ul><ul><li>No control on the format of the data. </li></ul><ul><li>Interface: int putchar( const int ) </li></ul><ul><li>Explaination: putchar() takes one argument of int type (char). e.g. – char ch = 'S'; putchar(ch); </li></ul><ul><li>It is implement as MACRO. It reads the data after pressing <RETURN> key. </li></ul><ul><li>fputchar() is its function implementation. </li></ul>
  75. 75. Unformatted Output – putch() <ul><li>Just another function like putchar(). </li></ul><ul><li>No control on the format of the data. </li></ul><ul><li>Interface: int putch( const int ) </li></ul><ul><li>Explaination: putch() function takes one argument of int type. e.g. – char ch='S'; putch(ch); </li></ul><ul><li>This is implemented as MACRO. The function equivalent is fputch(). </li></ul>
  76. 76. Unformatted Output – putw() <ul><li>Similar to putc () in all respects expect that the it writes an integer value instead of a character. </li></ul><ul><li>Interface: int putw( const int , FILE * ) </li></ul><ul><li>E.g. – int num; putw(num , stdout); </li></ul><ul><li>putw() function is a non-ANSI function and a similar function putwc() is used to write w_char used to store unicode character. </li></ul>
  77. 77. Unformatted Output – fputs() <ul><li>It writes string data to the specified file, monitor or printer and used to do so usually. </li></ul><ul><li>Interface: int fputs( const char * , FILE * ) </li></ul><ul><li>Explaination: fputs() function writes the string specified by the 1 st argument to the stream specified by the 2 nd argument and returns the number of bytes written. e.g. – char name[ 20 ] = &quot;Sudesh Kantila&quot;; fputs(name, stdout); </li></ul>
  78. 78. Unformatted Output – puts() <ul><li>It just writes string data to the monitor. </li></ul><ul><li>Interface: int puts( const char * ) </li></ul><ul><li>Explaination: puts() function writes the string and returns number of bytes written. e.g. – char name[ 20 ] = &quot;Sudesh Kantila&quot;; puts(name); </li></ul><ul><li>puts() function has less control over the string written and must be avoided. Use printf() function instead. </li></ul>
  79. 79. Formatted Output – fprintf() <ul><li>Using fprintf(), we can write data to any file pointed by a FILE *, monitor or printer. </li></ul><ul><li>Interface: int fprintf( FILE * , const char * ,...) </li></ul><ul><li>E.g. – char ch = 'A'; int num = 1; fprintf(stdout,&quot; %c%i &quot;,ch,num); </li></ul><ul><li>This is used specially in file handling. </li></ul><ul><li>It writes data to the stream specified by 1 st arg of the form specified by 2 nd arg and holded by subsequent arguments. It also returns the number of data items/ bytes written successfully. </li></ul>
  80. 80. Formatted Output – printf() <ul><li>Using printf(), we can write data to the Monitor. It is a restricted version of fprintf function limited to use stdout as first argument. </li></ul><ul><li>Interface: int printf( const char * ,...) </li></ul><ul><li>E.g. – char ch = 'A'; int num = 1; printf(&quot; %c%i &quot;,ch,num); </li></ul><ul><li>It writes data to the monitor of the form specified by 1 st arg and holded by subsequent arguments. It also returns the number of data items/ bytes written successfully. </li></ul>
  81. 81. Formatted Output – sprintf() <ul><li>Using sprintf(), we can write data to a string buffer. </li></ul><ul><li>Interface: int fprintf( const char * , const char * ,...) </li></ul><ul><li>E.g. – char ch[] = &quot;best&quot;; char * str = &quot;A1 is the &quot;; sprintf(str,&quot; %s &quot;,ch); /* str=&quot;A1 is the best&quot; */ </li></ul><ul><li>It writes data to the string specified by the 1 st arg of the form specified by 2 nd arg and holded by subsequent arguments. It also returns the number of data items/ bytes written successfully. </li></ul>
  82. 82. Standard FILE * streams <ul><li>stdin : </li></ul><ul><ul><li>STandarD INput stream. </li></ul></ul><ul><ul><li>Points to keyboard. </li></ul></ul><ul><ul><li>Buffered and may be redirected. </li></ul></ul><ul><li>stdout : </li></ul><ul><ul><li>STandarD OUTput stream. </li></ul></ul><ul><ul><li>Points to monitor. </li></ul></ul><ul><ul><li>Buffered stream and may be redirected. </li></ul></ul>
  83. 83. Standard FILE * streams <ul><li>stderr : </li></ul><ul><ul><li>STandarD ERRor stream. </li></ul></ul><ul><ul><li>Points to monitor. </li></ul></ul><ul><ul><li>Unbuffered and may not be redirected. </li></ul></ul><ul><li>stdprn : </li></ul><ul><ul><li>STandarD PRiNt stream. </li></ul></ul><ul><ul><li>Points to printer connect on LPT1 port. </li></ul></ul><ul><ul><li>Buffered and may be redirected. </li></ul></ul><ul><li>stdaux : </li></ul><ul><ul><li>STandarD AUXilary stream. </li></ul></ul><ul><ul><li>Points to communication port 1 e.g. COM1. </li></ul></ul><ul><ul><li>Buffered stream and may be redirected. </li></ul></ul>
  84. 84. Escape Sequences ' * ' <ul><li>Backslash character constants are used in output functions. </li></ul><ul><li>Each one of them represents one character, although they consist of two characters. </li></ul><ul><li>These character combinations are known as escape sequences. </li></ul><ul><li>E.g. : The symbol ‘ ’ stands for newline character printf(“Programming in C”); printf(“ ”); printf(“Next Line”); </li></ul>
  85. 85. Backslash Character Constants Constant Meaning ‘ a’ Audible alert (bell) ‘ ’ Back space ‘ f’ Form feed ‘ ’ New line ‘ ’ Carriage return ‘ ’ Horizontal tab ‘ v’ Vartical tab ‘ ’’ Single quote ‘ ”’ Double quote ‘ ?’ Question mark ‘ Backslash ‘ ’ null
  86. 86. This tutorial is not yet complete! <ul><li>Please note that this tutorial is still incomplete, you must attend the next class to continue the tutorial, which is necessary to learn the ‘C’ completely. </li></ul><ul><li>You must try to solve some problems and develop algorithms. Implement the algorithm in ‘C’ and run the program to see the result. </li></ul>
  87. 87. Query Time ? <ul><li>If you have any doubt in the topics taught in this session, please raise hand. </li></ul><ul><li>Doubts will be cleared one by one. </li></ul>
  88. 88. Thankyou! <ul><li>This presentation is available on http://www.secs.ac.in/downloads/cbykantila.pps http://www.secs.ac.in/downloads/cbykantila.ppsx </li></ul><ul><li>This can be accessed inside campus on //campus/public/tutorials/cbykantila.pps //campus/public/tutorials/cbykantila.ppsx (When prompted for username and password, provide “sample” both as username as well as password.) </li></ul><ul><li>For any problem in ‘C’, contact : Prof. Sudesh Kantila, [Sr. System Analyst],IT Deptt. Or write to: [email_address] </li></ul><ul><li>Some additional sample programs are also available on http://kantila.page.tl/ </li></ul>

×