1 Objectives • To understand the constructs of C Language. • To develop C Programs using basic programming constructs • To develop C programs using arrays and strings • To develop modular applications in C using functions • To develop applications in C using pointers and structures • To do input/output and file handling in C C PROGRAMMING
2 PROGRAMMING IN C
3 Background • C was originally developed in the 1970s, by Dennis Ritchie at Bell Telephone Laboratories, Inc. • C is a High level , general purpose structured programming language. Instructions of C consists of terms that are very closely same to algebraic expressions, consisting of certain English keywords such as if, else, for, do and while • C contains certain additional features that allows it to be used at a lower level , acting as bridge between machine language and the high level languages. • This allows C to be used for system programming as well as for applications programming
4 Background C is a C is a structured programming language. It is structured programming language. It is considered a high-level language considered a high-level language because it allows the because it allows the programmer to concentrate on the problem at hand programmer to concentrate on the problem at hand and not worry about the machine that the program and not worry about the machine that the program will be using. That is another reason why it is used by will be using. That is another reason why it is used by software developers whose applications have to run on software developers whose applications have to run on many different hardware platforms. many different hardware platforms.
5 C Programs It's time to write your first C program. It's time to write your first C program. Structure of a C Program Your First C Program Comments The Greeting Program Topics discussed in this section: Topics discussed in this section:
6 Structure of a C Program
7 The Greeting Program
8 The Greeting Program
9 Examples of Block Comments
10 Examples of Line Comments
11 Applications of C Programming
12 Applications of C Programming • Operating Systems. The first operating system to be developed using a high-level programming language was UNIX, which was designed in the C programming language. • Embedded Systems • GUI • New Programming Platforms • Google • Mozilla Firefox and Thunderbird. • MySQL. • Compiler Design.
13 Most Important Features of C Language • Simple and Efficient. • Fast. • Portability. • Extensibility. • Function-Rich Libraries. • Dynamic Memory Management. • Modularity With Structured Language. • Mid-Level Programming Language
Computer Science: A Structured Programming Approach Using C 14 • C language consist of some characters set, numbers and some special symbols. The character set of C consist of all the alphabets of English language. C consist of • Alphabets a to z, A to Z • Numeric 0,1 to 9 • Special Symbols {,},[,],?,+,-,*,/,%,!,;,and more • The words formed from the character set are building • blocks of C and are sometimes known as tokens. These tokens represent the individual entity of language. The following different types of token are used in C  1) Identifiers 2)Keywords 3)Constants  4) Operators 5)Punctuation Symbols The Character set of ‘C’
15 Identifiers One feature present in all computer languages is the One feature present in all computer languages is the identifier. Identifiers allow us to name data and other identifier. Identifiers allow us to name data and other objects in the program. Each identified object in the objects in the program. Each identified object in the computer is stored at a unique address. computer is stored at a unique address.
16 Rules for Identifiers
Identifiers  A 'C' program consist of two types of elements , user defined and system defined. Idetifiers is nothing but a name given to these elements.  An identifier is a word used by a programmer to name a variable , function, or label.  identifiers consist of letters and digits, in any order, except that the first charecter or lable.  Identifiers consist of letters and digits if any order,except that the first charecter must be letter.  Both Upper and lowercase letters can be used
18 C is a case-sensitive language. Note Note
19 Examples of Valid and Invalid Names
Keywords  Keywords are nothing but system defined identifiers.  Keywords are reserved words of the language.  They have specific meaning in the language and cannot be used by the programmer as variable or constant names  C is case senitive, it means these must be used as it is  32 Keywords in C Programming auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while
Variables  A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.  The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case- sensitive. There are following basic variable types − Type Description  char Typically a single octet(one byte). This is an integer type.  int The most natural size of integer for the machine.  float A single-precision floating point value.  double A double-precision floating point value.  void Represents the absence of type.
Constants  A constant is a value or an identifier whose value cannot be altered in a program. For example: 1, 2.5,  As mentioned, an identifier also can be defined as a constant. eg. const double PI = 3.14  Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program. Integer constants  A integer constant is a numeric constant (associated with number) without any fractional or exponential part. There are three types of integer constants in C programming:  decimal constant(base 10)  octal constant(base 8)  hexadecimal constant(base 16)
Constants Floating-point constants  A floating point constant is a numeric constant that has either a fractional form or an exponent form. For example: 2.0,0.0000234,-0.22E-5 Character constants  A character constant is a constant which uses single quotation around characters. For example: 'a', 'l', 'm', 'F' String constants  String constants are the constants which are enclosed in a pair of double-quote marks. For example: "good" ,"x","Earth is roundn"
Escape Sequences Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc. In order to use these characters, escape sequence is used.  For example: n is used for newline. The backslash ( ) causes "escape" from the normal way the characters are interpreted by the compiler.Escape Sequences Character  b Backspace  f Form feed  n Newline  r Return  t Horizontal tab  v Vertical tab  Backslash  ' Single quotation mark  " Double quotation mark  ? Question mark  0 Null character
25 Data Types
26 Character Types
27 Integer Types
28 sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long) Note Note
29 Typical Integer Sizes and Values for Signed Integers
30 Floating-point Types
31 sizeof (float) ≤ sizeof (double) ≤ sizeof (long double) Note Note
32 Type Summary
33 Variables Variables are named memory locations that have a type, Variables are named memory locations that have a type, such as integer or character, which is inherited from such as integer or character, which is inherited from their type. The type determines the values that a variable their type. The type determines the values that a variable may contain and the operations that may be used with may contain and the operations that may be used with its values. its values. Variable Declaration Variable Initialization Topics discussed in this section: Topics discussed in this section:
34 Variables
35 Examples of Variable Declarations and Definitions
36 Variable Initialization ‘B’
Computer Science: A Structured Programming Approach Using C 37 When a variable is defined, it is not initialized. We must initialize any variable requiring prescribed data when the function starts. Note Note
Computer Science: A Structured Programming Approach Using C 38 PROGRAM 2-2 Print Sum of Three Numbers
Computer Science: A Structured Programming Approach Using C 39 PROGRAM 2-2 Print Sum of Three Numbers (continued)
Computer Science: A Structured Programming Approach Using C 40 PROGRAM 2-2 Print Sum of Three Numbers (continued)
41 Constants Constants are data values that cannot be changed Constants are data values that cannot be changed during the execution of a program. Like variables, during the execution of a program. Like variables, constants have a type. In this section, we discuss constants have a type. In this section, we discuss Boolean, character, integer, real, complex, and string Boolean, character, integer, real, complex, and string constants. constants. Constant Representation Coding Constants Topics discussed in this section: Topics discussed in this section:
42 Symbolic Names for Control Characters
43 Examples of Integer Constants
44 Examples of Real Constants
Computer Science: A Structured Programming Approach Using C 45 FIGURE 2-13 Some Strings
Computer Science: A Structured Programming Approach Using C 46 FIGURE 2-14 Null Characters and Null Strings
Computer Science: A Structured Programming Approach Using C 47 Use single quotes for character constants. Use double quotes for string constants. Note Note
Computer Science: A Structured Programming Approach Using C 48 PROGRAM 2-3 Memory Constants
Computer Science: A Structured Programming Approach Using C 49 PROGRAM 2-3 Memory Constants (continued)
Operators in C:An operator is a symbol which operates on a value or a variable. For example: + is an operator to perform addition. C programming has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:  Arithmetic Operators  Increment and Decrement Operators  Assignment Operators  Relational Operators  Logical Operators  Conditional Operators  Bitwise Operators  Special Operators
Arithmetic Operator Operator Meaning of Operator + addition or unary plus - subtraction or unary minus * multiplication / division % remainder after division ( modulo division)
Increment and Decrement Operators 1. C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. 2. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. 3. These two operators are unary operators, meaning they only operate on a single operand. eg. int a=10, b=100 ++a = 11 --b = 99
C Assignment Operators  An assignment operator is used for assigning a value to a variable. The most common assignment operator is =  Operator Example Same as  = a = b a = b  += a += b a = a+b  -= a -= b a = a-b  *= a *= b a = a*b  /= a /= b a = a/b  %= a %= b a = a%b
C Relational Operators  A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.  Relational operators are used in decision making and loops. Operator Meaning of Operator Example  == Equal to 5 == 3 returns 0  > Greater than 5 > 3 returns 1  < Less than 5 < 3 returns 0  != Not equal to 5 != 3 returns 1  >= Greater than or equal to 5 >= 3 returns 1  <= Less than or equal to 5 <= 3 return 0
55 C Relational Operators  <, <=, > >=, ==, != are the relational operators. The expression operand1 relational-operator operand2 takes a value of 1(int) if the relationship is true and 0(int) if relationship is false.  Example int a = 25, b = 30, c, d; c = a < b; d = a > b; value of c will be 1 and that of d will be 0.
Logical Operators Computer Science: A Structured Programming Approach Using C 56  &&, || and ! are the three logical operators.  expr1 && expr2 has a value 1 if expr1 and expr2 both are nonzero.  expr1 || expr2 has a value 1 if expr1 and expr2 both are nonzero.  !expr1 has a value 1 if expr1 is zero else 0.  Example If(marks >= 40 && attendance >= 75 ) grade = ‘P’ if(marks < 40 || attendance < 75 ) grade = ‘N’
Lectures on Numerical Methods 57 Precedence and Associativity of C Operators
Lectures on Numerical Methods 58 Precedence and Associativity of C Operators
59 Type Conversions  The operands of a binary operator must have a the same type and the result is also of the same type.  Integer division: c = (9 / 5)*(f - 32) The operands of the division are both int and hence the result also would be int. For correct results, one may write c = (9.0 / 5.0)*(f - 32)  In case the two operands of a binary operator are different, but compatible, then they are converted to the same type by the compiler. The mechanism (set of rules) is called Automatic Type Casting. c = (9.0 / 5)*(f - 32)  It is possible to force a conversion of an operand. This is called Explicit Type casting. c = ((float) 9 / 5)*(f - 32)
60 Automatic Type Casting 1. char and short operands are converted to int 2. Lower data types are converted to the higher data types and result is of higher type. 3. The conversions between unsigned and signed types may not yield intuitive results. 4. Example float f; double d; long l; int i; short s; d + f f will be converted to double i / s s will be converted to int l / i i is converted to long; long result Hierarchy Double float long Int Short and char
61 Explicit Type Casting  The general form of a type casting operator is  (type-name) expression  It is generally a good practice to use explicit casts than to rely on automatic type conversions.  Example C = (float)9 / 5 * ( f – 32 )  float to int conversion causes truncation of fractional part  double to float conversion causes rounding of digits  long int to int causes dropping of the higher order bits.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-62 Control Structures in C • Control structures Control structures control the flow of execution in a program or function. • There are three kinds of execution flow: – Sequence Sequence: • the execution of the program is sequential. – Selection Selection: • A control structure which chooses alternative to execute. – Repetition Repetition: • A control structure which repeats a group of statements. • We will focus on the selection selection control structure in this chapter.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-63 Conditions • A program may choose among alternative statements by testing the value of key variables. – e.g., if( your_grade > 60 ) printf(“you are passed!”); • Condition Condition is an expression that is either false (represented by 0) or true (represented by 1). – e.g., “your_grade > 60” is a condition. • Conditions may contain relational relational or equality equality operators operators, and have the following forms. – variable relational-operator relational-operator variable (or constant) – variable equality-operator equality-operator variable (or constant)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-64 Operators Used in Conditions Operator Meaning Type < Less than Relational > Greater than Relational <= Less than or equal to Relational >= Greater than or equal to Relational == Equal to Equality != Not equal to Equality
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-65 Examples of Conditions Operator Condition Meaning <= x <= 0 x less than or equal to 0 < Power < MAX_POW Power less than MAX_POW == mom_or_dad == ‘M’ mom_or_dad equal to ‘M’ != num != SETINEL num not equal to SETINEL
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-66 Logical Operators • There are three kinds of logical operators logical operators. . – &&: and – ||: or – !: not • Logical expression Logical expression is an expression which uses one or more logical operators, e.g., – (temperature > 90.0 && humidity > 0.90) – !(n <= 0 || n >= 100).
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-67 The Truth Table of Logical Operators Op 1 Op 2 Op 1 && Op2 Op 1 || Op2 nonzero nonzero 1 1 nonzero 0 0 1 0 nonzero 0 1 0 0 0 0 Op 1 ! Op 1 nonzero 0 0 1
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-68 Operator Precedence • An operator’s precedence precedence determines its order of evaluation. • Unary operator Unary operator is an operator that has only one operand. – !, +(plus sign), -(minus sign), and &(address of) – They are evaluated second only after function calls. Operator Precedence function calls highest ! + - & * / % + - < <= >= > == != && || = lowest
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-69 Evaluation for !flag || (y + z >= x - z) Evaluation tree The result of this expression is true
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-70 Comparing Characters • We can also compare characters in C using the relational relational and equality operators equality operators. Expression Value ‘9’ >= ‘0’ 1 (true) ‘a’ < ‘e’ 1 (true) ‘Z’ == ‘z’ 0 (false) ‘a’ <= ‘A’ system dependent
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-71 DeMorgan’s Theorem • DeMorgan’s theorem DeMorgan’s theorem gives us a way of transforming a logical expression into its complement. – The complement of expr1 && expr2 is comp1 || comp2, where comp1 and comp2 are the complement of expr1 and expr2, respectively. – The complement of expr1 || expr2 is comp1 && comp2. • e.g., age > 25 && (status == ‘S’ || status ==‘D’) is equal to !(age <=25 || (status != ‘S’) && status != ‘D’)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-72 The if Statement • The if statement is the primary selection selection control structure. • Syntax: if (condition) statement; else statement; • An example of two alternatives: if ( rest_heart_rate > 56 ) printf(“Keep up your exercise program!n”); else printf(“Your heart is in excellent health!n”); • An example of one alternative: if ( x != 0.0 ) product = product * x;
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-73 Flowchart • Flowchart Flowchart is a diagram that shows the step-by- step execution of a control structure. – A diamond-shaped box diamond-shaped box represents a decision. – A rectangular box rectangular box represents an assignment statement or a process.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-74 Flowcharts Flowcharts of if Statements with (a) Two Alternatives and (b) One Alternative Decision Decision
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-75 Nested if Statements • Nested Nested if if statement statement is an if statement with another another if if statement statement as its true task or false task. • e.g., if (road_status == ‘S’) else printf(“Drive carefully!n”); if (temp > 0) { printf(“Wet roads ahead!n”); }else{ printf(“Icy roads ahead!n”); }
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-76 An Example for the Flowchart of Nested if Statements Another if statement Main if statement
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-77 Multiple-Alternative Decisions • If there are many alternatives, it is better to use the syntax of multiple-alternative decision multiple-alternative decision. • Syntax: if (condition1) statement1 else if (condition2) statement2 … else if (conditionn) statementn else statemente
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-78 An Example of Multiple-Alternative Decisions
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-79 The switch Statement • The switch statement is used to select one of several alternatives when the selection is based on the value of a single variable a single variable or an expression an expression. switch (controlling expression) { case label1: statement1 break; case label2: statement2 break; … case labeln: statementn break; default: statementd; } If the result of this controlling expression matches label1, execute staement1 and then break this switch block. If the result matches none of all labels, execute the default statementd.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-80 An Example of a switch Statement with Type char Case Labels class is a char variable. Two or more cases can execute the same statement.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-81 Homework #3 (1/2) • Write a program that prompts the user to input input the boiling point the boiling point in degree Celsius. • The program should output output the substance the substance corresponding to the boiling point listed in the table. • The program should output the message “substance “substance unknown” unknown” when it does not match any substance. Substance Boiling point Water 100°C Mercury 357°C Copper 1187°C Silver 2193°C Gold 2660°C
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-82 Homework #3 (2/2) • Examples of the scenario of your program. • You can determine the substance within a range within a range of boiling points of boiling points to get bonus (e.g., +5 degrees). – Please refer to pages 207-208 in the text book. • You can apply any technique in this chapter. Please input: 357 The substance is Mercury. Please input: 3333 Substance unknown. Please input: 359 The substance is Mercury.
5-83 Repetition in Programs • In most software, the statements in the program may need to repeat for many times. – e.g., calculate the value of n!. – If n = 10000, it’s not elegant to write the code as 1*2*3*…*10000. • Loop Loop is a control structure that repeats a group of steps in a program. – Loop body Loop body stands for the repeated statements. • There are three C loop control statements: – while while, for for, and do-while do-while.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-84 Flow Diagram of Loop Choice Process e.g., calculate the value of n! e.g., read the content in a file
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-85 Comparison of Loop Choices (1/2) Kind When to Use C Structure Counting loop We know how many loop repetitions will be needed in advance. while, for Sentinel- controlled loop Input of a list of data ended by a special value while, for Endfile- controlled loop Input of a list of data from a data file while, for
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-86 Comparison of Loop Choices (2/2) Kind When to Use C Structure Input validation loop Repeated interactive input of a value until a desired value is entered. do-while General conditional loop Repeated processing of data until a desired condition is met. while, for
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-87 The while Statement in C • The syntax of while statement in C: while (loop repetition condition loop repetition condition) statement • Loop repetition condition Loop repetition condition is the condition which controls the loop. • The statement is repeated as long as the loop repetition condition is true true. • A loop is called an infinite loop infinite loop if the loop repetition condition is always true.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-88 An Example of a while Loop Statement Loop repetition condition Loop control variable Loop control variable is the variable whose value controls loop repetition. In this example, count_emp is the loop control variable.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-89 Flowchart for a while Loop Loop repetition condition Statement
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-90 Compound Assignment Operators (1/2) • The loop body usually consists of statements of the form: variable = variable op expression. – e.g., count_emp = count_emp + 1; • C provides compound assignment operators compound assignment operators which enable a more concise notation for this kind of statements. – “ “variable op = expression” variable op = expression” is the same to “variable = variable op expression.”
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-91 Compound Assignment Operators (2/2) Simple Assignment Operators Compound Assignment Operators count_emp = count_emp + 1; count_emp += 1; time = time -1; time -= 1; product = product * item; product *= item; total = total / number; total /= number; n = n % (x+1); n %= x+1;
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-92 The for Statement in C • The syntax of for statement in C: for (initialization expression initialization expression; loop repetition condition loop repetition condition; update expression update expression) statement • The initialization expression initialization expression set the initial value of the loop control variable. • The loop repetition condition loop repetition condition test the value of the loop control variable. • The update expression update expression update the loop control variable.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-93 An Example of the for Loop Loop repetition condition Initialization Expression Update Expression count_emp is set to 0 initially. count_emp should not exceed the value of number_emp. count_emp is increased by one after each iteration.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-94 Increment and Decrement Operators • The statements of increment and decrement are commonly used in the for loop. • The increment (i.e., ++ ++) or decrement (i.e., -- --) operators are the frequently used operators which take only one operand. • The increment/decrement operators increase or decrease the value of the single operand. – e.g., for (int i = 0; i < 100; i++ i++){ … } – The variable i increase one after each iteration.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-95 Comparison of Prefix and Postfix Increments The value of the expression (that uses the ++/-- operators) depends on the position of the operator. The value of j is increased The value of j is not increased
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-96 Sentinel-Controlled Loops • Sometimes we may not know how many times the loop will repeat. • One way to do this is to choose a sentinel value sentinel value as an end marker. – The loop exits when the sentinel value sentinel value is read. • If the user wish to exit the loop, he or she has to input the sentinel value sentinel value. – It is similar to the “logout” function in many applications.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-97 An Example of Sentinel-Controlled while Loops If the user wish to exit the loop, he or she has to input -99.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-98 An Example of Endfile-Controlled Loops • fscanf fscanf is a function used to read file. • EOF EOF stands for the special value of end-file returned by fscanf fscanf. • This loop repeats until reading the end of the file.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-99 Nested Loops • Nested loops consist of an outer loop outer loop with one or more inner loops inner loops. • e.g., for (i=1;i<=100;i++){ for(j=1;j<=50;j++){ … } } • The above loop will run for 100*50 iterations. Inner loop Outer loop
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-100 The do-while Statement in C • The syntax of do-while statement in C: do statement while (loop repetition condition loop repetition condition); • The statement is first executed. • If the loop repetition condition loop repetition condition is true, the statement is repeated. • Otherwise, the loop is exited.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-101 An Example of the do-while Loop /* Find even number input */ do{ printf(“Enter a value: ”); scanf(“%d”, &num); }while (num % 2 !=0) This loop will repeat if the user inputs odd number.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-102 Homework #4 (1/2) • Write a program that prompts the user to input an integer n. • Draw a triangle with n levels by star symbols. For example, n = 3, * ** *** • After drawing the triangle, repeat the above process until the user input a negative integer.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-103 Homework #4 (2/2) • An usage scenario: Please input: 2 * ** Please input: 3 * ** *** Please input: -9 Thank you for using this program.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-104

Basics of C Programming for Placement .ppt

  • 1.
    1 Objectives • To understandthe constructs of C Language. • To develop C Programs using basic programming constructs • To develop C programs using arrays and strings • To develop modular applications in C using functions • To develop applications in C using pointers and structures • To do input/output and file handling in C C PROGRAMMING
  • 2.
  • 3.
    3 Background • C wasoriginally developed in the 1970s, by Dennis Ritchie at Bell Telephone Laboratories, Inc. • C is a High level , general purpose structured programming language. Instructions of C consists of terms that are very closely same to algebraic expressions, consisting of certain English keywords such as if, else, for, do and while • C contains certain additional features that allows it to be used at a lower level , acting as bridge between machine language and the high level languages. • This allows C to be used for system programming as well as for applications programming
  • 4.
    4 Background C is a Cis a structured programming language. It is structured programming language. It is considered a high-level language considered a high-level language because it allows the because it allows the programmer to concentrate on the problem at hand programmer to concentrate on the problem at hand and not worry about the machine that the program and not worry about the machine that the program will be using. That is another reason why it is used by will be using. That is another reason why it is used by software developers whose applications have to run on software developers whose applications have to run on many different hardware platforms. many different hardware platforms.
  • 5.
    5 C Programs It's timeto write your first C program. It's time to write your first C program. Structure of a C Program Your First C Program Comments The Greeting Program Topics discussed in this section: Topics discussed in this section:
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
    12 Applications of CProgramming • Operating Systems. The first operating system to be developed using a high-level programming language was UNIX, which was designed in the C programming language. • Embedded Systems • GUI • New Programming Platforms • Google • Mozilla Firefox and Thunderbird. • MySQL. • Compiler Design.
  • 13.
    13 Most Important Featuresof C Language • Simple and Efficient. • Fast. • Portability. • Extensibility. • Function-Rich Libraries. • Dynamic Memory Management. • Modularity With Structured Language. • Mid-Level Programming Language
  • 14.
    Computer Science: AStructured Programming Approach Using C 14 • C language consist of some characters set, numbers and some special symbols. The character set of C consist of all the alphabets of English language. C consist of • Alphabets a to z, A to Z • Numeric 0,1 to 9 • Special Symbols {,},[,],?,+,-,*,/,%,!,;,and more • The words formed from the character set are building • blocks of C and are sometimes known as tokens. These tokens represent the individual entity of language. The following different types of token are used in C  1) Identifiers 2)Keywords 3)Constants  4) Operators 5)Punctuation Symbols The Character set of ‘C’
  • 15.
    15 Identifiers One feature presentin all computer languages is the One feature present in all computer languages is the identifier. Identifiers allow us to name data and other identifier. Identifiers allow us to name data and other objects in the program. Each identified object in the objects in the program. Each identified object in the computer is stored at a unique address. computer is stored at a unique address.
  • 16.
  • 17.
    Identifiers  A 'C'program consist of two types of elements , user defined and system defined. Idetifiers is nothing but a name given to these elements.  An identifier is a word used by a programmer to name a variable , function, or label.  identifiers consist of letters and digits, in any order, except that the first charecter or lable.  Identifiers consist of letters and digits if any order,except that the first charecter must be letter.  Both Upper and lowercase letters can be used
  • 18.
    18 C is acase-sensitive language. Note Note
  • 19.
    19 Examples of Validand Invalid Names
  • 20.
    Keywords  Keywords arenothing but system defined identifiers.  Keywords are reserved words of the language.  They have specific meaning in the language and cannot be used by the programmer as variable or constant names  C is case senitive, it means these must be used as it is  32 Keywords in C Programming auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while
  • 21.
    Variables  A variableis nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.  The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case- sensitive. There are following basic variable types − Type Description  char Typically a single octet(one byte). This is an integer type.  int The most natural size of integer for the machine.  float A single-precision floating point value.  double A double-precision floating point value.  void Represents the absence of type.
  • 22.
    Constants  A constantis a value or an identifier whose value cannot be altered in a program. For example: 1, 2.5,  As mentioned, an identifier also can be defined as a constant. eg. const double PI = 3.14  Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program. Integer constants  A integer constant is a numeric constant (associated with number) without any fractional or exponential part. There are three types of integer constants in C programming:  decimal constant(base 10)  octal constant(base 8)  hexadecimal constant(base 16)
  • 23.
    Constants Floating-point constants  Afloating point constant is a numeric constant that has either a fractional form or an exponent form. For example: 2.0,0.0000234,-0.22E-5 Character constants  A character constant is a constant which uses single quotation around characters. For example: 'a', 'l', 'm', 'F' String constants  String constants are the constants which are enclosed in a pair of double-quote marks. For example: "good" ,"x","Earth is roundn"
  • 24.
    Escape Sequences Sometimes, itis necessary to use characters which cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc. In order to use these characters, escape sequence is used.  For example: n is used for newline. The backslash ( ) causes "escape" from the normal way the characters are interpreted by the compiler.Escape Sequences Character  b Backspace  f Form feed  n Newline  r Return  t Horizontal tab  v Vertical tab  Backslash  ' Single quotation mark  " Double quotation mark  ? Question mark  0 Null character
  • 25.
  • 26.
  • 27.
  • 28.
    28 sizeof (short) ≤sizeof (int) ≤ sizeof (long) ≤ sizeof (long long) Note Note
  • 29.
    29 Typical Integer Sizesand Values for Signed Integers
  • 30.
  • 31.
    31 sizeof (float) ≤sizeof (double) ≤ sizeof (long double) Note Note
  • 32.
  • 33.
    33 Variables Variables are namedmemory locations that have a type, Variables are named memory locations that have a type, such as integer or character, which is inherited from such as integer or character, which is inherited from their type. The type determines the values that a variable their type. The type determines the values that a variable may contain and the operations that may be used with may contain and the operations that may be used with its values. its values. Variable Declaration Variable Initialization Topics discussed in this section: Topics discussed in this section:
  • 34.
  • 35.
    35 Examples of VariableDeclarations and Definitions
  • 36.
  • 37.
    Computer Science: AStructured Programming Approach Using C 37 When a variable is defined, it is not initialized. We must initialize any variable requiring prescribed data when the function starts. Note Note
  • 38.
    Computer Science: AStructured Programming Approach Using C 38 PROGRAM 2-2 Print Sum of Three Numbers
  • 39.
    Computer Science: AStructured Programming Approach Using C 39 PROGRAM 2-2 Print Sum of Three Numbers (continued)
  • 40.
    Computer Science: AStructured Programming Approach Using C 40 PROGRAM 2-2 Print Sum of Three Numbers (continued)
  • 41.
    41 Constants Constants are datavalues that cannot be changed Constants are data values that cannot be changed during the execution of a program. Like variables, during the execution of a program. Like variables, constants have a type. In this section, we discuss constants have a type. In this section, we discuss Boolean, character, integer, real, complex, and string Boolean, character, integer, real, complex, and string constants. constants. Constant Representation Coding Constants Topics discussed in this section: Topics discussed in this section:
  • 42.
    42 Symbolic Names forControl Characters
  • 43.
  • 44.
  • 45.
    Computer Science: AStructured Programming Approach Using C 45 FIGURE 2-13 Some Strings
  • 46.
    Computer Science: AStructured Programming Approach Using C 46 FIGURE 2-14 Null Characters and Null Strings
  • 47.
    Computer Science: AStructured Programming Approach Using C 47 Use single quotes for character constants. Use double quotes for string constants. Note Note
  • 48.
    Computer Science: AStructured Programming Approach Using C 48 PROGRAM 2-3 Memory Constants
  • 49.
    Computer Science: AStructured Programming Approach Using C 49 PROGRAM 2-3 Memory Constants (continued)
  • 50.
    Operators in C:Anoperator is a symbol which operates on a value or a variable. For example: + is an operator to perform addition. C programming has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:  Arithmetic Operators  Increment and Decrement Operators  Assignment Operators  Relational Operators  Logical Operators  Conditional Operators  Bitwise Operators  Special Operators
  • 51.
    Arithmetic Operator Operator Meaningof Operator + addition or unary plus - subtraction or unary minus * multiplication / division % remainder after division ( modulo division)
  • 52.
    Increment and Decrement Operators 1.C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. 2. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. 3. These two operators are unary operators, meaning they only operate on a single operand. eg. int a=10, b=100 ++a = 11 --b = 99
  • 53.
    C Assignment Operators An assignment operator is used for assigning a value to a variable. The most common assignment operator is =  Operator Example Same as  = a = b a = b  += a += b a = a+b  -= a -= b a = a-b  *= a *= b a = a*b  /= a /= b a = a/b  %= a %= b a = a%b
  • 54.
    C Relational Operators A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.  Relational operators are used in decision making and loops. Operator Meaning of Operator Example  == Equal to 5 == 3 returns 0  > Greater than 5 > 3 returns 1  < Less than 5 < 3 returns 0  != Not equal to 5 != 3 returns 1  >= Greater than or equal to 5 >= 3 returns 1  <= Less than or equal to 5 <= 3 return 0
  • 55.
    55 C Relational Operators  <,<=, > >=, ==, != are the relational operators. The expression operand1 relational-operator operand2 takes a value of 1(int) if the relationship is true and 0(int) if relationship is false.  Example int a = 25, b = 30, c, d; c = a < b; d = a > b; value of c will be 1 and that of d will be 0.
  • 56.
    Logical Operators Computer Science:A Structured Programming Approach Using C 56  &&, || and ! are the three logical operators.  expr1 && expr2 has a value 1 if expr1 and expr2 both are nonzero.  expr1 || expr2 has a value 1 if expr1 and expr2 both are nonzero.  !expr1 has a value 1 if expr1 is zero else 0.  Example If(marks >= 40 && attendance >= 75 ) grade = ‘P’ if(marks < 40 || attendance < 75 ) grade = ‘N’
  • 57.
    Lectures on NumericalMethods 57 Precedence and Associativity of C Operators
  • 58.
    Lectures on NumericalMethods 58 Precedence and Associativity of C Operators
  • 59.
    59 Type Conversions  Theoperands of a binary operator must have a the same type and the result is also of the same type.  Integer division: c = (9 / 5)*(f - 32) The operands of the division are both int and hence the result also would be int. For correct results, one may write c = (9.0 / 5.0)*(f - 32)  In case the two operands of a binary operator are different, but compatible, then they are converted to the same type by the compiler. The mechanism (set of rules) is called Automatic Type Casting. c = (9.0 / 5)*(f - 32)  It is possible to force a conversion of an operand. This is called Explicit Type casting. c = ((float) 9 / 5)*(f - 32)
  • 60.
    60 Automatic Type Casting 1.char and short operands are converted to int 2. Lower data types are converted to the higher data types and result is of higher type. 3. The conversions between unsigned and signed types may not yield intuitive results. 4. Example float f; double d; long l; int i; short s; d + f f will be converted to double i / s s will be converted to int l / i i is converted to long; long result Hierarchy Double float long Int Short and char
  • 61.
    61 Explicit Type Casting The general form of a type casting operator is  (type-name) expression  It is generally a good practice to use explicit casts than to rely on automatic type conversions.  Example C = (float)9 / 5 * ( f – 32 )  float to int conversion causes truncation of fractional part  double to float conversion causes rounding of digits  long int to int causes dropping of the higher order bits.
  • 62.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-62 Control Structures in C • Control structures Control structures control the flow of execution in a program or function. • There are three kinds of execution flow: – Sequence Sequence: • the execution of the program is sequential. – Selection Selection: • A control structure which chooses alternative to execute. – Repetition Repetition: • A control structure which repeats a group of statements. • We will focus on the selection selection control structure in this chapter.
  • 63.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-63 Conditions • A program may choose among alternative statements by testing the value of key variables. – e.g., if( your_grade > 60 ) printf(“you are passed!”); • Condition Condition is an expression that is either false (represented by 0) or true (represented by 1). – e.g., “your_grade > 60” is a condition. • Conditions may contain relational relational or equality equality operators operators, and have the following forms. – variable relational-operator relational-operator variable (or constant) – variable equality-operator equality-operator variable (or constant)
  • 64.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-64 Operators Used in Conditions Operator Meaning Type < Less than Relational > Greater than Relational <= Less than or equal to Relational >= Greater than or equal to Relational == Equal to Equality != Not equal to Equality
  • 65.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-65 Examples of Conditions Operator Condition Meaning <= x <= 0 x less than or equal to 0 < Power < MAX_POW Power less than MAX_POW == mom_or_dad == ‘M’ mom_or_dad equal to ‘M’ != num != SETINEL num not equal to SETINEL
  • 66.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-66 Logical Operators • There are three kinds of logical operators logical operators. . – &&: and – ||: or – !: not • Logical expression Logical expression is an expression which uses one or more logical operators, e.g., – (temperature > 90.0 && humidity > 0.90) – !(n <= 0 || n >= 100).
  • 67.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-67 The Truth Table of Logical Operators Op 1 Op 2 Op 1 && Op2 Op 1 || Op2 nonzero nonzero 1 1 nonzero 0 0 1 0 nonzero 0 1 0 0 0 0 Op 1 ! Op 1 nonzero 0 0 1
  • 68.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-68 Operator Precedence • An operator’s precedence precedence determines its order of evaluation. • Unary operator Unary operator is an operator that has only one operand. – !, +(plus sign), -(minus sign), and &(address of) – They are evaluated second only after function calls. Operator Precedence function calls highest ! + - & * / % + - < <= >= > == != && || = lowest
  • 69.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-69 Evaluation for !flag || (y + z >= x - z) Evaluation tree The result of this expression is true
  • 70.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-70 Comparing Characters • We can also compare characters in C using the relational relational and equality operators equality operators. Expression Value ‘9’ >= ‘0’ 1 (true) ‘a’ < ‘e’ 1 (true) ‘Z’ == ‘z’ 0 (false) ‘a’ <= ‘A’ system dependent
  • 71.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-71 DeMorgan’s Theorem • DeMorgan’s theorem DeMorgan’s theorem gives us a way of transforming a logical expression into its complement. – The complement of expr1 && expr2 is comp1 || comp2, where comp1 and comp2 are the complement of expr1 and expr2, respectively. – The complement of expr1 || expr2 is comp1 && comp2. • e.g., age > 25 && (status == ‘S’ || status ==‘D’) is equal to !(age <=25 || (status != ‘S’) && status != ‘D’)
  • 72.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-72 The if Statement • The if statement is the primary selection selection control structure. • Syntax: if (condition) statement; else statement; • An example of two alternatives: if ( rest_heart_rate > 56 ) printf(“Keep up your exercise program!n”); else printf(“Your heart is in excellent health!n”); • An example of one alternative: if ( x != 0.0 ) product = product * x;
  • 73.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-73 Flowchart • Flowchart Flowchart is a diagram that shows the step-by- step execution of a control structure. – A diamond-shaped box diamond-shaped box represents a decision. – A rectangular box rectangular box represents an assignment statement or a process.
  • 74.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-74 Flowcharts Flowcharts of if Statements with (a) Two Alternatives and (b) One Alternative Decision Decision
  • 75.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-75 Nested if Statements • Nested Nested if if statement statement is an if statement with another another if if statement statement as its true task or false task. • e.g., if (road_status == ‘S’) else printf(“Drive carefully!n”); if (temp > 0) { printf(“Wet roads ahead!n”); }else{ printf(“Icy roads ahead!n”); }
  • 76.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-76 An Example for the Flowchart of Nested if Statements Another if statement Main if statement
  • 77.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-77 Multiple-Alternative Decisions • If there are many alternatives, it is better to use the syntax of multiple-alternative decision multiple-alternative decision. • Syntax: if (condition1) statement1 else if (condition2) statement2 … else if (conditionn) statementn else statemente
  • 78.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-78 An Example of Multiple-Alternative Decisions
  • 79.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-79 The switch Statement • The switch statement is used to select one of several alternatives when the selection is based on the value of a single variable a single variable or an expression an expression. switch (controlling expression) { case label1: statement1 break; case label2: statement2 break; … case labeln: statementn break; default: statementd; } If the result of this controlling expression matches label1, execute staement1 and then break this switch block. If the result matches none of all labels, execute the default statementd.
  • 80.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-80 An Example of a switch Statement with Type char Case Labels class is a char variable. Two or more cases can execute the same statement.
  • 81.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-81 Homework #3 (1/2) • Write a program that prompts the user to input input the boiling point the boiling point in degree Celsius. • The program should output output the substance the substance corresponding to the boiling point listed in the table. • The program should output the message “substance “substance unknown” unknown” when it does not match any substance. Substance Boiling point Water 100°C Mercury 357°C Copper 1187°C Silver 2193°C Gold 2660°C
  • 82.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-82 Homework #3 (2/2) • Examples of the scenario of your program. • You can determine the substance within a range within a range of boiling points of boiling points to get bonus (e.g., +5 degrees). – Please refer to pages 207-208 in the text book. • You can apply any technique in this chapter. Please input: 357 The substance is Mercury. Please input: 3333 Substance unknown. Please input: 359 The substance is Mercury.
  • 83.
    5-83 Repetition in Programs •In most software, the statements in the program may need to repeat for many times. – e.g., calculate the value of n!. – If n = 10000, it’s not elegant to write the code as 1*2*3*…*10000. • Loop Loop is a control structure that repeats a group of steps in a program. – Loop body Loop body stands for the repeated statements. • There are three C loop control statements: – while while, for for, and do-while do-while.
  • 84.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-84 Flow Diagram of Loop Choice Process e.g., calculate the value of n! e.g., read the content in a file
  • 85.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-85 Comparison of Loop Choices (1/2) Kind When to Use C Structure Counting loop We know how many loop repetitions will be needed in advance. while, for Sentinel- controlled loop Input of a list of data ended by a special value while, for Endfile- controlled loop Input of a list of data from a data file while, for
  • 86.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-86 Comparison of Loop Choices (2/2) Kind When to Use C Structure Input validation loop Repeated interactive input of a value until a desired value is entered. do-while General conditional loop Repeated processing of data until a desired condition is met. while, for
  • 87.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-87 The while Statement in C • The syntax of while statement in C: while (loop repetition condition loop repetition condition) statement • Loop repetition condition Loop repetition condition is the condition which controls the loop. • The statement is repeated as long as the loop repetition condition is true true. • A loop is called an infinite loop infinite loop if the loop repetition condition is always true.
  • 88.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-88 An Example of a while Loop Statement Loop repetition condition Loop control variable Loop control variable is the variable whose value controls loop repetition. In this example, count_emp is the loop control variable.
  • 89.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-89 Flowchart for a while Loop Loop repetition condition Statement
  • 90.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-90 Compound Assignment Operators (1/2) • The loop body usually consists of statements of the form: variable = variable op expression. – e.g., count_emp = count_emp + 1; • C provides compound assignment operators compound assignment operators which enable a more concise notation for this kind of statements. – “ “variable op = expression” variable op = expression” is the same to “variable = variable op expression.”
  • 91.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-91 Compound Assignment Operators (2/2) Simple Assignment Operators Compound Assignment Operators count_emp = count_emp + 1; count_emp += 1; time = time -1; time -= 1; product = product * item; product *= item; total = total / number; total /= number; n = n % (x+1); n %= x+1;
  • 92.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-92 The for Statement in C • The syntax of for statement in C: for (initialization expression initialization expression; loop repetition condition loop repetition condition; update expression update expression) statement • The initialization expression initialization expression set the initial value of the loop control variable. • The loop repetition condition loop repetition condition test the value of the loop control variable. • The update expression update expression update the loop control variable.
  • 93.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-93 An Example of the for Loop Loop repetition condition Initialization Expression Update Expression count_emp is set to 0 initially. count_emp should not exceed the value of number_emp. count_emp is increased by one after each iteration.
  • 94.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-94 Increment and Decrement Operators • The statements of increment and decrement are commonly used in the for loop. • The increment (i.e., ++ ++) or decrement (i.e., -- --) operators are the frequently used operators which take only one operand. • The increment/decrement operators increase or decrease the value of the single operand. – e.g., for (int i = 0; i < 100; i++ i++){ … } – The variable i increase one after each iteration.
  • 95.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-95 Comparison of Prefix and Postfix Increments The value of the expression (that uses the ++/-- operators) depends on the position of the operator. The value of j is increased The value of j is not increased
  • 96.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-96 Sentinel-Controlled Loops • Sometimes we may not know how many times the loop will repeat. • One way to do this is to choose a sentinel value sentinel value as an end marker. – The loop exits when the sentinel value sentinel value is read. • If the user wish to exit the loop, he or she has to input the sentinel value sentinel value. – It is similar to the “logout” function in many applications.
  • 97.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-97 An Example of Sentinel-Controlled while Loops If the user wish to exit the loop, he or she has to input -99.
  • 98.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-98 An Example of Endfile-Controlled Loops • fscanf fscanf is a function used to read file. • EOF EOF stands for the special value of end-file returned by fscanf fscanf. • This loop repeats until reading the end of the file.
  • 99.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-99 Nested Loops • Nested loops consist of an outer loop outer loop with one or more inner loops inner loops. • e.g., for (i=1;i<=100;i++){ for(j=1;j<=50;j++){ … } } • The above loop will run for 100*50 iterations. Inner loop Outer loop
  • 100.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-100 The do-while Statement in C • The syntax of do-while statement in C: do statement while (loop repetition condition loop repetition condition); • The statement is first executed. • If the loop repetition condition loop repetition condition is true, the statement is repeated. • Otherwise, the loop is exited.
  • 101.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-101 An Example of the do-while Loop /* Find even number input */ do{ printf(“Enter a value: ”); scanf(“%d”, &num); }while (num % 2 !=0) This loop will repeat if the user inputs odd number.
  • 102.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-102 Homework #4 (1/2) • Write a program that prompts the user to input an integer n. • Draw a triangle with n levels by star symbols. For example, n = 3, * ** *** • After drawing the triangle, repeat the above process until the user input a negative integer.
  • 103.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 5-103 Homework #4 (2/2) • An usage scenario: Please input: 2 * ** Please input: 3 * ** *** Please input: -9 Thank you for using this program.
  • 104.
    Copyright ©2004 PearsonAddison-Wesley. All rights reserved. 4-104

Editor's Notes

  • #3 Developed early 1970’s
  • #4 Developed early 1970’s
  • #26 wchar_t is a wide character:  The increased datatype size allows for the use of larger coded character sets. Width is compiler specific (not portable).