Download presentation
Presentation is loading. Please wait.
1
Introduction to the C Language
UNIT-1 Introduction to the C Language Objectives Understand the basic structure of a program in C . Learn the commands used in UNIX/LINUX and MS-DOS for compiling and running a program in C. Obtain a preliminary idea of the keywords in C. Learn the data types, variables, constants, operators, and expressions in C. Understand and grasp the precedence and associativity rules of operators in C. Get acquainted with the rules of type conversions in C. Get to know the input and output streams that exist in C to carry out the input and output Tasks. Understand that C provides a set of input and output functions Learn to use the formatted input and output functions scanf() and printf() for handling multiple input and output. 1
2
Basics of C Ken Thompson at Bell Labs, USA, wrote his own variant over Martin Richards’s Basic Combined Programming Language and called it B . Dennis Ritchie, at Bell Labs, is credited for designing C in the early 1970s. Today C is a high-level language which also provides the capabilities that enable the programmers to ‘get in close’ with the hardware and allows them to interact with the computer on a much lower level. 2
3
WHY LEARN C? There are a large number of programming languages in the world today even so, there are several reasons to learn C, some of which are stated as follows: a . C is quick. b . C is a core language : In computing, C is a general purpose, cross-platform, block structured procedural, imperative computer programming language. c . C is a small language: C has only thirty-two keywords. This makes it relatively easy to learn compared to bulkier languages. d . C is portable. 3
4
WHY LEARN C? Currently, the most commonly-used language for embedded systems “High-level assembly” Very portable: compilers exist for virtually every processor Easy-to-understand compilation Produces efficient code Fairly concise 4
5
Algorithm 5
6
Definition of Algorithm:
An algorithm for solving a problem “a finite sequence of unambiguous, executable steps or instructions, which, if followed would ultimately terminate and give the solution of the problem”. Note the keywords: Finite set of steps; Unambiguous; Executable; Terminates; 6
7
Characteristics of Algorithm
Correctness Complexity --- time, space (memory), etc Ease of understanding Ease of coding Ease of maintainence 7
8
Ex:Average of two Input: Two numbers Add the two numbers
Divide the result by 2 Return the result by step 2 End 8
9
Ex:Adding two (n-digit) numbers
Input: Two positive m-digit decimal numbers (a and b) am, am-1, …., a1 bm, bm-1, …., b1 Output: The sum c = a + b cm+1, cm, cm-1, …., c1 (Note: In the textbook, it was am-1,…,a1,a0 … ) 9
10
Assignments 1. Write an Algorithm for how to prepare Tea.(Real life Example..) 2. Write an Algorithm to check person is eligible to vote or not 10
11
Pseudo Code Mixture of computer language and English
Somewhere in between precise enough to describe what is meant without being too tediuos Examples: Let c be 0; Sort the list of numbers in increasing order; 11
12
Pseudocode for three constructs
12
13
Simple Algorithms: Prime Numbers
Algorithm to determine if n is prime Given: A positive integer n Question: Is n a prime number? What do we know? “A number n is prime iff n has no positive factors except 1 and n” Idea: Express it “algorithmically” “n is not divisible by any positive number k such that 1 < k < n.” or k=2,3,4,…,(n-1) What we already have: A module Divisible(m,n) to check divisibility We can use it as a primitive 13
14
Ex:Prime(in pseudo-code)
Prime(n) (* To determine if n is prime *) begin for k 2 to (n-1) do if Divisible(k,n) then (Print “False” & exit) else (* Do nothing *) endfor Print “True” & Stop end; Note: Prime uses the module Divisible(k,n) Exercise it with: Prime (5); Prime (4); Prime (55); Prime (41); 14
15
Flowchart (Dictionary) A schematic representation of a sequence of operations, as in a manufacturing process or computer program. (Technical) A graphical representation of the sequence of operations in an information system or program. Information system flowcharts show how data flows from source documents through the computer to final distribution to users. Program flowcharts show the sequence of instructions in a single program or subroutine. Different symbols are used to draw each type of flowchart. 15
16
Flowchart A Flowchart shows logic of an algorithm
emphasizes individual steps and their interconnections e.g. control flow from one action to the next 16
17
Flowchart Symbols 17
18
Assignment 1 Step 1: Input M1,M2,M3,M4 Step 2: GRADE (M1+M2+M3+M4)/4
START Input M1,M2,M3,M4 GRADE(M1+M2+M3+M4)/4 IS GRADE<50 PRINT “FAIL” STOP Y N Step 1: Input M1,M2,M3,M4 Step 2: GRADE (M1+M2+M3+M4)/4 Step 3: if (GRADE <50) then Print “FAIL” else Print “PASS” endif 18
19
Assignment 2 Write an algorithm and draw a flowchart to convert the length in feet to centimeter. Pseudocode: Input the length in feet (Lft) Calculate the length in cm (Lcm) by multiplying LFT with 30 Print length in cm (LCM) 19
20
Assignment 2 Algorithm Step 1: Input Lft Step 2: Lcm Lft x 30
Step 3: Print Lcm Flowchart START Input Lft Lcm Lft x 30 Print Lcm STOP 20
21
Assignment 3 Write an algorithm and draw a flowchart that will read the two sides of a rectangle and calculate its area. Pseudocode Input the width (W) and Length (L) of a rectangle Calculate the area (A) by multiplying L with W Print A 21
22
Assignment 3 Algorithm Step 1: Input W,L Step 2: A L x W
Step 3: Print A START Input W, L A L x W Print A STOP 22
23
Assignment 4 Write an algorithm and draw a flowchart that will calculate the roots of a quadratic equation Hint: d = sqrt ( ), and the roots are: x1 = (–b + d)/2a and x2 = (–b – d)/2a 23
24
Assignment 4 Pseudocode:
Input the coefficients (a, b, c) of the quadratic equation Calculate d Calculate x1 Calculate x2 Print x1 and x2 24
25
Assignment 4 Algorithm: Step 1: Input a, b, c Step 2: d sqrt ( )
START Input a, b, c d sqrt(b x b – 4 x a x c) Print x1 ,x2 STOP x1 (–b + d) / (2 x a) X2 (–b – d) / (2 x a) Algorithm: Step 1: Input a, b, c Step 2: d sqrt ( ) Step 3: x1 (–b + d) / (2 x a) Step 4: x2 (–b – d) / (2 x a) Step 5: Print x1, x2 25
26
BACKGROUND Developed between 1969 and 1973 along with Unix
Due mostly to Dennis Ritchie Designed for systems programming Operating systems Utility programs Compilers Filters Evolved from B, which evolved from BCPL
27
BACKGROUND Taxonomy of the C Language
A much more significant update was made in 1999 known as C99. The changes incorporated into the standard C99 are summarized in the following list. Extensions to the character type to support non-English characters. A Boolean type Extensions to the integer type. Inclusion of type definitions in the for statement. Addition of imaginary and complex types Incorporation of c++ style line comment(//).
28
Topics discussed in this section:
C Programs (1 of 7) It's time to write your first C program! This section will take you through all the basic parts of a C program so that you will be able to write it. Topics discussed in this section: Structure of a C Program Your First C Program Comments The Greeting Program Structure of a C Program:
29
C Programs (2 of 7) Structure of a C Program:
Every C program is made of one or more preprocessor commands, a global declaration section, and one or more functions. The global declaration section comes at the beginning of the program. The basic idea of global declarations is that they are visible to all parts of the program. The work of the program is carried out by its functions, blocks of code that accomplish a task within a program. The function must be named is main. The main function is the starting point for the program. All functions in a program, including main, are divided into 2 sections: 1) The declaration section 2) The statement section. The declaration section is at the beginning of the function, it describes the data will be using in the function. Declarations in a function are known as local declarations because they are visible only to the function.
30
C Programs (3 of 7) Structure of a C Program:
The statement section contains the instructions to the computer that cause it to do something, such as add 2 numbers . The preprocessor directives are special instructions to the preprocessor that tell it how to prepare the program for compilation. One of the most important preprocessor command is include. The include command tells the preprocessor that we need information from selected libraries known as header files. Your First C Program: Our first C program is very simple. No preprocessor commands No global declarations. No local definitions. It only prints simple message
31
C Programs (4 of 7) Preprocessor Commands:
Preprocessor commands comes at the beginning of the program. They can start in any column , usually start in column 1 All the preprocessor commands start with pound sign(#). They tell the compiler to include the standard input/output library file in the program The complete syntax is #include<stdio.h> stdio->standard input/output header file. Executable part the program begins with the function main. Syntax is int main(void) Main starts with open brace({) and ends with close brace(}) Main contains two statements 1)to print message 2) to terminate the program. First c program to print hello world u1_ex1.c
32
C Programs (5 of 7) Comments:
Although it reasonable to expect that a good programmer should be able to read code, sometimes the meaning of a section is not entirely clear. This is especially true in C. Thus it is helpful if the person who writes the code places some comments in the to help the reader. Comments are ignored by the compiler. To identify the comments, C uses 2 different formats. Line comments 2. Block comments. 3. A block comment is used when the comment will span several lines block comment opening token is /* and closing token is */ Example of Block Comments:
33
Inner comment not allowed
C Programs (6 of 7) Comments: 4.The second format, the line comment, uses. two slashes (//) to identify the comment. This format does not require an end of comment token. The line comment can start anywhere on the line. Example of Line Comments: Note: comments can not be nested Inner comment not allowed Closing token /* =================/* */===================*/ ignored Left on its own
34
C Programs (7 of 7) The Greeting Program:
We have some comments at the beginning. We have also shown comments to identify the declaration and statements section of our program C program with both line and block comments u1_ex2.c
35
Identifiers (1 of 3) One feature present in all computer languages is the identifier. Identifiers allow us to name data and other objects in the program. Each identified object in the computer is stored at a unique address. If we didn’t have identifiers, we would have to know and use object’s addresses. Instead, we simply give data identifiers and let the compiler keep track of where they are physically located. The rules for identifiers are: The first character must be alphabetic character(A-Z, a-z) or underscore. Must contain only alphabetic characters(A-Z, a-z), digits(0-9) or underscore. First 63 characters of an identifier are significant. Cannot duplicate a keyword. Usually the identifies in the C system libraries start with an underscore, not an application programs.
36
Identifiers (2 of 3) auto _Complex doube for int short switch volatile
The last rule says the name we create cannot be keywords. Keywords also known as reserved words C language contains 37 keywords that cannot be used ad identifies. auto _Complex doube for int short switch volatile _Bool const else goto long signed typedef while break continue enum if register sizeof union case default extern _imaginary restrict static unsigned char do float inline return struct void
37
Identifiers (3 of 3) The underscore used in identifiers is to make it descriptive. When the names contain multiple words, the underscore makes it easier to read . An identifier must start with a letter or underscore: it may not have a space or a hyphen. C is a case-sensitive language. Examples of Valid and Invalid Names: C program for identifiers, keywords u1_ex3.c
38
Types (1 of 7) A type defines a set of values and a set of operations that can be applied on those values. For example, a light switch can be compared to a computer type. It has a set of two values, on and off. Only two operations can be applied to a light switch: turn-on and turn-off. The C language has defined set of types that can divided into four general categories: void Integral floating-point Derived Data Types:
39
Types (2 of 7) Void Type: The void type designated by the keyword void, has values and no operations. Which mainly used with functions and pointers. Integral Type: The C language has three integral types: Boolean ,character and integer. Integral types cannot contain fractional part; they are whole numbers Boolean: With the release of C99, the C language incorporated a Boolean data type named by French mathematician George Boole A Boolean data type represent only two values: true and false The Boolean type, referred to by the keyword bool, is stored in memory as 0(false) or 1(true) character: To a computer, a character is any value that can be represented in the computer’s alphabet, or as it better known , its character set. C standard provides two character types: char and wchar_t c program for character data type u1_ex6.c
40
Types (3 of 7) character: Most computers use the American standard code for Information Interchange (ASCII) . Most computer uses 1 byte or 8-bits to store char data types. To support non-English languages, the c99 standard created wide character type(wchat_t). Integer: An integer type is a number without fractional part. C supports four different sizes of integer data type: short int, int, long int and long long int. C defines these data types so that they can be organized from the smallest to the largest . The type also defines the size of the field in which data can be stored To know the size of any data type, C provides an operator, sizeof, that will tell us the exact size in bytes. Each integer can be signed or unsigned. If the integer is signed , then one bit must be used for a signed (0 is plus, 1 is minus). The unsigned integer can store a positive number that is twice as large as the signed integr of same size. C has a library, limits.h that contains information about integers. Ex: minimum integer value is INT_MIN maximum integer value is INT_MAX c program for integer data type u1_ex4.c
41
Types (4 of 7) Integral Types:
Note: sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long) Typical integer sizes and range of values for signed Integers: c program for integer data type u1_ex5.c
42
Note: sizeof (float) ≤ sizeof (double) ≤ sizeof (long double)
Types (5 of 7) Floating-Point Types: The C language recognizes three floating-pint types: real, imaginary and complex. There is a standard library, float.h, for the floating point values The real type values are always signed. Real: The Real type holds values that consist of an integral and fractional part, such as The C language supports three different sizes of real types: float, double and long double. C defines these data types so that they can be organized from the smallest to the largest. Note: sizeof (float) ≤ sizeof (double) ≤ sizeof (long double) C program for floating point data type u1_ex7.c
43
Types (6 of 7) Imaginary Type:
An imaginary number is used extensively in mathematics and engineering. An imaginary number is a real number multiplied by square root of -1. The imaginary type is of three different sizes : float imaginary, double imaginary and long double imaginary. Most implementations do not support imaginary type. Complex Type: C defines a complex type, which is implemented by most compilers. A complex number is a combination of a real and imaginary number. The complex type is of three different sizes: float complex, double complex and long double complex The size needs to be same in both the real and imaginary part.
44
Types (7 of 7) Type Summary:
45
Variables (1 of 2) Variable Declaration:
Variables are named memory locations that have a type, such as integer or character, which is inherited from their type. The type determines the values that a variable may contain and the operations that may be used with its values. Variable Declaration: Each variable in our program must be declared and defined. In C, a declaration is used to name an object, such as a variable. Definitions are used to create an object. A variable is declared and defined at the same time. Declaration gives them symbolic name and definition reserves memory for them. Once defined, variables are used to hold the data that are reqired by the program for its operation A variable can be any data type, such as char, int or real but a variable cannot be void.
46
Variables (2 of 2) Variable Initialization:
We can initialize a variable at the same time that we declare it by including an initializer, the initializer establishes the first value that the variable will contain. To initialize a variable when it is define, the identifier is followed by assignment operator and the initializer, which is the value the variable is to have when the function starts. Example: int count=0; int count=0,sum=0 Note: When a variable is defined, it is not initialized. We must initialize any variable requiring prescribed data when the function starts. When variables are defined ,they usually contain garbage(meaningless) values. C program to illustrate the concept of a variable u1_ex8.c
47
Constants (1 of 7) Boolean constants:
Constants are data values that cannot be changed during the execution of a program. Like variables, constants have a type. Here, we discuss Boolean, character, integer, real, complex, and string constants. Boolean constants: A Boolean data type can take only two values, so only two symbols to represent a Boolean data type. The values are true and false. A Boolean value can have only two values: 1(true) and 0(false) To use Boolean constants we have to include the Boolean library stdbool.h Character constants: The character constants are enclosed between two single quote. Ex: ‘a’ or ‘x’ or ‘2’ In addition to the character, we can also use a backslash(\) before the character. The backslash(\) is known as the escape character. It is used when the character cannot be printed or when it can be entered from the keyboard. Ex: \n ->new line Wide character constants are coded by prefixing the constant with an L. ex: L ‘X’ Most computers use ASCII character set Boolean & character constants program u1_ex9.c
48
Constants (2 of 7) Symbolic names for control characters:
Character constants program u1_ex10.c
49
Constants (3 of 7) Integer Constants:
1. Integers are always stored in their binary form. They simply coded as we use them in everyday life. Ex x=15. Integer constants program u1_ex11.c
50
Constants (4 of 7) Real Constants:
The default form of real constants is double. If we want the resulting data type to be float or long double, we must use a code to specify the desired data type. You must anticipate f and F are used for float and l and L are used for long double. Real constants program u1_ex12.c
51
Constants (5 of 7) Complex Constants:
Complex constants are coded as two parts, the real part and the imaginary part, separated by a plus sign. The real part is coded using the real format rules. The imaginary part is coded as a areal number times(*) the imaginary constant(_Complex_I). Here we need to include the complex library complex.h The default form of complex constants is double. The two components of a complex constant must be of the same precision, that is, if the real part is type double, then the imaginary part must also be type double.
52
Constants (6 of 7) String Constants:
A string constant is a sequence of zero or more characters enclosed in double quotes It is important to understand the difference between the null character and an empty string. The null character represents no value. As a character it is eight zero bits. An empty string is a string containing nothing. Use single quotes for character constants. Use double quotes for string constants. All constants program u1_ex13.c
53
Constants (7 of 7) Coding Constants:
There are 3 types of coding constants Literal constants: A literal is an unnamed constant used to specify data. if we know that the data cannot be changed, then we can simply code the data value itself in a statement. Ex: the literal 5 is used in the following statement a=b+5 2. Defined constants: Another way to designate a constant is to use the preprocessor command define, which is prefaced with pound sign(#), usually placed at beginning of the program. Ex: #define SALES_TAX_RATE The preprocessor does not evaluate the code__ it just blindly makes the substitution. 3. memory constants : The third way to use a constant is with memory constants. Memory constants use a C type qualifier, const, to indicate that the data cannot be changed. Its format is: Ex: const type identifier=value Here the content of memory location are fixed. Coding constants program u1_ex14.c
54
Input/output statements (1 of 11)
Although our programs have implicitly shown how to print messages, we have not formally discussed how we use C facilities to input and output data. Streams: In C data is input to and output from a stream A stream is source of or destination for data. It is Associated with physical device, such as a terminal, or with a file stored in auxiliary memory. C uses two forms of streams : text and binary. A text stream consists of sequence of characters divided into lines with line terminated by a newline(\n). A binary stream consists of sequence of data values such as integer, real, or complex using their memory representation. Here we assume that the source of data is the keyboard and destination of data is the monitor. Keyboard is known as standard input and monitor is known as standard output
55
Input/output statements (2 of 11)
Formatted Input/Output: The C language provides two formatting functions: printf for output formatting and scanf for input formatting. Output formatting: printf The printf function takes a set of data values, converts them to a text stream using formatting instructions contained in a format control string, and sends the resulting text stream to the standard output(monitor). printf is data to text stream converter. The syntax of printf function is int printf(“ format control string”, argument list);
56
Input/output statements (3 of 11)
Output formatting: printf Format control string Input and output functions use a format control string. Format control string describes how data is to be formatted when read or write. Format control string may also contain the text to be printed, such as instructions to the user, captions to make the output more readable. We can also print control characters, such as (\t), (\n), (a) by including them in format control string.
57
Input/output statements (4 of 11)
Output formatting: printf Conversion specification To insert data into the stream, we use a conversion specification that contain a start token (%), a conversion code, and up to four optional modifiers as shown below. The number, order and type of conversion specification must match the number, order and type of the parameters in the list. Otherwise it causes unpredictable results resulting in termination of input/output function. 3. The first element is a conversion specification token (%) and the last element is the conversion code. Both of these elements are required, the other elements are optional
58
Input/output statements (5 of 11)
Conversion codes Type Size Code Example char none c %c short int h d %hd int %d long int l %ld long long int ll %lld float f %f double long double %lf Precision: If a floating point number is being printed, then we may specify the number of decimal places to be printed with precision modifier. The precision modifier has the format .m ex: %.2f Where m is the number of decimal digits. If no precision is specified printf prints six decimal positions.
59
Input/output statements (6 of 11)
Width modifier: A width modifier may be used to specify the minimum number of position in the output. It is very useful to align the output in columns, such as we need to print a column of numbers. It we don’t use a width modifier, each output value will take just enough room for the data. Ex: often width and precision are used %2hd //short integer-2 print positions %4d //integer -4 print positions %8ld //long int-8 print positions %7.2f //float-7 print positions. 2 decimal places %10.3f //long double -10 print positions. 3 decimal places Flag modifier: Flags allows the user to format the output in a desired fashion. Four output flags: Justification Padding Sign Alternate form Program for width, precision and size u1_ex15.c
60
Input/output statements (7 of 11)
The table defines the flag type, flag code and formatting Program for printf statement with flags u1_ex16.c
61
Input/output statements (8 of 11)
Input formatting: scanf The standard input formatting function in C is scanf . This function takes a text stream from keyboard, extracts and formats data from the stream according to a format control string, and the stores the data in specified program variables. scanf requires variable addresses in the address list. Syntax of scanf statement is int scanf (“format control string”, & argument list); Scanf statement with sizes u1_ex17.c
62
Input/output statements (9 of 11)
Format control string Like the format control string for prints, the control string for scanf is enclosed in a set of quotation marks and contains one or more conversion specifications that describe the data types.
63
Input/output statements (10 of 11)
Conversion Specification To format data from the input stream ,we use a conversion specification that contains a start token (%), a conversion code, and up to three optional modifiers as shown below. There is no precision in an input conversion specification. There is only one flag for input formatting, the assignment suppression flag(*). This flag tells scanf that the next input field is to be read but not stored. It is discarded. Ex: scanf(%d%*c%f”, &a,&b) It reads integer, character and real numbers but only stores integer and real. 4. The width modifier specifies the maximum number of characters to be read .With input formatting width is maximum, not a minimum Program for scanf statement with flags u1_ex18.c
64
Input/output statements (11 of 11)
Input formatting summary
65
Operators (1 of 17) An operator is a symbol which helps the user to give instruction to the computer to do a certain mathematical or logical manipulations. Operators are used in C language program to operate on data and variables. C has a rich set of operators which can be classified as follows: 1. Arithmetic operators. 2. Relational Operators. 3. Logical Operators. 4. Assignment Operators. 5. Increments and Decrement Operators. 6. Conditional Operators. 7. Bitwise Operators. 8. Special Operators.
66
Operators (2 of 17) Arithmetic Operators
All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in C language. Unary operations operate on a singe operand, Therefore the number 5 when operated by unary – will have the value –5. Operator Meaning + Addition or Unary Plus - Subtraction or Unary Minus * Multiplication / Division % Modulus Operator
67
Operators (3 of 17) 1.Arithmetic Operators
Examples of arithmetic operators are: x + y , x - y , x * y , x / y , x % y The modulus operator is a special operator in C language which evaluates the remainder of the operands after division. Integer Arithmetic When an arithmetic operation is performed on two integers than such an operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 x + y = 32 , x – y = 22 , x * y = 115 , x % y = 2 , x / y = 5 Floating point arithmetic When an arithmetic operation is preformed on two real numbers such an operation is called floating point arithmetic. Let x = 14.0 and y = 4.0 then x + y = 18.0 , x – y = 10.0 , x * y = 56.0 , x / y = 3.50 Mixed mode arithmetic When one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is called as mixed mode arithmetic. If any one operand is of real type then the result will always be real t 15/10.0 = 1.5 Program for arithmetic operators u1_ex19.c
68
Operators (4 of 17) 2.Relational Operators
Often it is required to compare the relationship between operands and bring out a decision and program accordingly. This is when the relational operator come into picture. C supports the following relational operators. Ex: It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using relational operators. (6.5 <= 25) , (-65 > 0) , (10 < 7 + 5) which result in either TRUE OR FALSE Relational expressions are used in decision making statements of C language such as if, while and for statements to decide the course of action of a running program Operator Meaning < is less than <= is less than or equal to > is greater than >= is greater than or equal to == is equal to != is not equal to Program for relational operators u1_ex20.c
69
Operators (5 of 17) 3. Logical Operators
C has the following logical operators; they compare or evaluate logical and relational expressions. Operator Meaning && Logical AND || Logical OR ! Logical NOT Op1 Op2 Op1 & op2 Op1|| op2 Nonzero 1 Logical AND (&&) If both the expressions are true then the whole compound expression is true. Example: a > b && x = = 10 Logical OR (||) If any one of the 2 expressions is true. Example: a < m || a < n Logical NOT (!) The logical not operator evaluates to true if the expression is false and evaluates to false if the expression is true. For example: ! (x >= y) Program for logical operators u1_ex21.c
70
Operators (6 of 17) 4. Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression. Example: x = a + b In addition, C has a set of shorthand assignment operators of the form. var oper = exp; Example: x + = 1 is same as x = x + 1 The commonly used shorthand assignment operators are as follows Shorthand assignment operators Statement with simple assignment operator Statement with shorthand operator a = a + 1 a += 1 a = a – 1 a -= 1 a = a * (n+1) a *= (n+1) a = a / (n+1) a /= (n+1) a = a % b a %= b Program for shorthand Assignment operators u1_ex22.c
71
Operators (7 of 17) 5. Increment and Decrement Operators
The increment and decrement operators are one of the unary operators which are very useful in C language. They are extensively used in for and while loops. The syntax of the operators is given below 1. ++ variable name 2. variable name++ 3. – –variable name 4. variable name– – The increment operator ++ adds the value 1 to the current value of operand. The decrement operator – – subtracts the value 1 from the current value of operand.
72
Operators (8 of 17) 5. Increment and Decrement Operators
++variable name and variable name++ mean the same thing when they form statements independently. They behave differently when they are used in expression on the right hand side of an assignment statement. Consider the following m = 5; y = ++m; (prefix) In this case the value of y and m would be 6 Suppose if we rewrite the above statement as y = m++; (post fix) Then the value of y will be 5 and that of m will be 6. Program for increment/ decrement operators u1_ex23.c
73
Operators (9 of 17) 6. Conditional or Ternary Operator
The conditional operator consists of 2 symbols the question mark (?) and the colon (:). The syntax for a ternary operator is as follows: exp1 ? exp2 : exp3 The ternary operator works as exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes the value of the expression. If exp1 is false,exp3 is evaluated and its value becomes the value of the expression. Note that only one of the expression is evaluated. For example: a = 10; b = 15; x = (a > b) ? a : b Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x. Output Input 2 integers : 45 34 The largest of two numbers is 45 Program for conditional operators u1_ex24.c
74
Operators (10 of 17) 7. Bitwise Operators
The C language is well suited to system programming because it contains operators that can manipulate data at the bit level. Those operators are used for testing, complementing or shifting bits to the right on left. C has two categories of bitwise operators that operate on data at the bit level: 1. Logical bitwise operators and 2. Shift bitwise operators. Logical bitwise operators: Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise Exclusive OR << Shift left >> Shift right
75
Operators (11 of 17) ~a a^b a|b a&b b a 1
7. Bitwise Operators Truth table ~a a^b a|b a&b b a 1 Program for bitwise operators u1_ex25.c
76
Operators (12 of 17) For unsigned data type, bits positions vacated
7. Bitwise Shift Operators The shift operators moves bits to the right or left. Bitwise shift-right operator: The bitwise shift right (>>) is a binary operator that requires two integral operands . The first operand is the value to be shifted. The second operand specifies the number of bits to be shifted. Ex: a >>= 5; /* shift right 5 bits */ For unsigned data type, bits positions vacated by shift are filled with zeros.
77
Operators (13 of 17) 7. Bitwise Right-Shift Operators
When we shift a binary numbers, the right-shift operator divides by a power of 2. If we shift a binary number two places to the right, we are dividing by 4. If we shift it three places , we are dividing by 8. 2 shift value Divide by Shift Operator 1 2 >>1 4 >>2 3 8 >>3 16 >>4 ….. ……. …… n 2n >>n
78
Operators (14 of 17) 7. Bitwise Left-Shift Operators The bitwise shift right (<<) is a binary operator that requires two integral operands . The first operand is the value to be shifted. The second operand specifies the number of bits to be shifted. Ex: a <<=3; /* shift right 5 bits */ Bits positions vacated by shift are filled with zeros
79
Operators (15 of 17) 7. Bitwise Left-Shift Operators
When we shift a binary numbers, the Left-shift operator multiplies by a power of 2. If we shift a binary number two places to the left, we are multiplying by 4. If we shift it three places , we are multiplying by 8. 2 shift value Multiplies by Shift Operator 1 2 <<1 4 <<2 3 8 <<3 16 <<4 …. …….. …… n 2n <<n Program for bitwise shift operators u1_ex26.c
80
Operators (16 of 17) 8. Special Operators
C supports some special operators of interest such as comma operator, size of operator, pointer operators (& and *) and member selection operators (. and ->). The size of and the comma operators are discussed here. The Comma Operator The comma operator can be used to link related expressions together. A comma linked list of expressions are evaluated left to right and value of right most expression is the value of the combined expression. For example the statement value = (x = 10, y = 5, x + y); First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest precedence in operators the parenthesis is necessary. Some examples of comma operator are In for loops: for (n=1, m=10, n <=m; n++,m++) In while loops While (c=getchar(), c != ‘10’) Exchanging values t = x, x = y, y = t; . Program for comma operators u1_ex27.c
81
Operators (17 of 17) 8. Special Operators The size of Operator
The operator size of gives the size of the data type or variable in terms of bytes occupied in the memory. The operand may be a variable, a constant or a data type qualifier. Example m = sizeof (sum); n = sizeof (long int); k = sizeof (235L); The size of operator is normally used to determine the lengths of arrays and structures when their sizes are not known to the programmer. It is also used to allocate memory space dynamically to variables during the execution of the program Program for sizeof operators u1_ex28.c
82
Expressions (1 of 9) An expression is a sequence of operands and operators that reduce to a single value. Expressions can be simple or complex. An operator is a syntactical token that requires an action be taken. An operand is an object on which an operation is performed; it receives an operator’s action . A simple expression contains only one operator. Ex: 2+5 A complex expression contains more than one operator. Ex: 2+5*7 An expression always reduces to a single value. We can divide simple expressions into six categories based on number of operands, relative position of the operand and operator and the precedence of operator.
83
Expressions (2 of 9) Primary Expressions
The most elementary type of expression is a primary expression. A primary expression consists of only one operand with no operator. In C, the operand in the primary expression can be a name, a constant, or a parenthesized expression. Names: A name is any identifier for a variable, a function, or any other object in the language. Examples of some names used as primary expressions. Ex: a b12 price calc INT_MAX SIZE Literal Constants: The second type of primary expression is the literal constant. A literal is a piece of data whose value cannot be changed during execution of the program. Ex: ‘A’ “Wel come” Parenthetical expressions: The third type of primary expression is the parenthetical expression. Any value enclosed in parentheses must be reducible to a single value and is therefore a primary expression. Ex: (2 * 3+4) (a= b*6 ).
84
Expressions (3 of 9) Postfix Expressions
The postfix expression consists of operand followed by operator. Some of the post fix expressions are function call, postfix increment, and postfix decrement. The form of postfix expression is Function call: All the function calls are postfix expressions. The function is the operand and the operator is the parentheses that follows the name. parentheses may contain arguments or empty. Ex: printf(“hello world”) scanf() Postfix increment/decrement: In the post increment/ decrement, the variable value incremented /decremented by 1. Program for postfix expressions u1_ex29.c
85
Expressions (4 of 9) Prefix Expressions
In prefix expressions, the operator comes before the operand Prefix Increment/Decrement: In C, we have only two prefix operators that form prefix expressions: prefix increment prefix decrement Prefix increment and decrement operators are shorthand notations for adding or subtracting 1 from variable. The operand of a prefix expression must be a variable. The value of (++a) is same as (a=a+1). Program for prefix expressions u1_ex30.c
86
Expressions (5 of 9) Note If ++ is after the operand, as in a++, the increment takes place after the expression is evaluated. If ++ is before the operand, as in ++a, the increment takes place before the expression is evaluated.
87
Expressions (6 of 9) Unary Expressions sizeof Unary plus/minus
A unary expression, like a prefix expression, consists of one operator and one operand and also the operator comes before the operand. sizeof The sizeof operator tells us the size in bytes, of a type or a primary expression. Ex: sizeof(int), sizeof(345.23), sizeof(x) Unary plus/minus Cast operator The cast operator converts one expression type to another. Ex: convert an integer to real number float(x)
88
Expressions (7 of 9) Binary Expressions Multiplicative Expressions
Binary expressions are formed by an operand-operator-operand combination. Multiplicative Expressions Multiplicative expressions include the operators multiply, divide, modulus operators. These operators have the higher priority among the binary operators and are therefore evaluated first. Both operands of the modulo operator (%) must be integral type. Ex: 10*3 //evaluates to 30 10/3 // evaluates to 3 true*4 // evaluates to 4 true/4 // evaluates to 0 ‘A’*2 // evaluates to 130 ‘A’/2 // evaluates to 32 22.3*2 // evaluates to /2 // evaluates to 11/15 10%3 // evaluates to 1 3/5 // evaluates to 0 ‘A’%2 // evaluates to 5 3%5 // evaluates to3 22.3%2 //error Program for integer binary expressions u1_ex31.c
89
Expressions (8 of 9) Additive Expressions Assignment Expressions
In additive expressions, the second operand is added to or subtracted from the first operand , depend on the operator used. Additive operators are evaluated after multiplicative expressions. Ex: 3+7 //evaluates to 10 3-7 //evaluates to -4 Assignment Expressions The assignment expression evaluates the operand on the right side of the operator(=) and places its value in the variable on the left. The value of the total expression is the value of the expression on the right of the assignment operator(=) The left operand in an assignment expression must be a single variable. There are two forms of assignment Simple assignment. Compound assignment. Program for floating point binary expressions u1_ex32.c
90
Expressions (9 of 9) Simple Assignment Compound Assignment
Simple assignment is found in algebraic expressions. Three examples of simple assignments are shown below a=5 b=x+1 i=i+1 Compound Assignment A compound assignment is a shorthand notation for a simple assignment. It requires that the left operand be repeated as a part of the right expression Program for compound assignment expressions u1_ex33.c
91
Precedence and Associativity (1 of 4)
Precedence is used to determine the order in which different operators in a complex expression are evaluated . C extents the concept to 15 levels. Ex: 2+3*4=(2+(3*4))=14 -b++=(-(b++)) Associativity Associativity is used to determine the order in which operators with the same precedence are evaluated in a complex expression. Precedence is applied before associativity to determine the order in which expressions are evaluated. Associativity can be left-to-right or right-to-left. Program for precedence of operators u1_ex34.c
92
Precedence and Associativity (2 of 4)
Left to Right Associativity All the operators have the same precedence. Their associativity is from left to right. so they are grouped as follows Ex: 3* 8 / 4 % 4 * 5 Right to Left Associativity All the operators have the same precedence. Their associativity is from right to left. so they are grouped as follows Ex: a += b *= c -= 5 which is (a=a+(b=b*(c=c-5))) Program for Assocoativity of operators u1_ex35.c
93
Precedence and Associativity (3 of 4) ++ -- + - ! ~ (type) * & sizeof
Operator Description Precedence Associativity ( ) [ ] . -> ++ -- Parentheses (function call) Brackets (array subscript) Member selection via object name Member selection via pointer Postfix increment/decrement 1 left-to-right ! ~ (type) * & sizeof Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (convert value to temporary value of type) Dereference Address (of operand) Determine size in bytes on this implementation 2 right-to-left * / % Multiplication/division/modulus 3 + - Addition/subtraction 4 << >> Bitwise shift left, Bitwise shift right 5
94
Precedence and Associativity (4 of 4)
Operator Description Precedence Associativity < <= > >= Relational less than/less than or equal to Relational greater than/greater than or equal to 6 left-to-right == != Relational is equal to/is not equal to 7 & Bitwise AND 8 ^ Bitwise exclusive OR 9 | Bitwise inclusive OR 10 && Logical AND 11 | | Logical OR 12 ? : Ternary conditional 13 right-to-left = += -= *= /= %= &= ^= |= <<= >>= Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment 14 , Comma (separate expressions) 15
95
Expression Evaluation (1 of 2)
Now we evaluate expressions as we know precedence, associativity of operators Expressions without side effects Ex: a*4+b/2-c*b consider a=3 b=4 c=5 Replace variables by their values 3 * / 2 – 5 * 4 Apply precedence rules (3 * 4) + (4 / 2) – (5 * 4) Apply Associativity rules as they are left to right associative (((3 * 4) + (4 / 2)) – (5 * 4)) In evaluation of this expressions there are no side effects
96
Expression Evaluation (2 of 2)
Expressions with side effects Now look for example with side effects and parenthesized expressions. Ex: --a * ( 3 + b ) / 2 – c++ * b Assume a=3 b=4 c=5 Calculate the value of parenthesized expressions --a * 7 / 2 – c++ * b Evaluate postfix expression --a * 7 / 2 – 5 * b Evaluate prefix expression 2 * 7 / 2 – 5 * b Now apply multiply and division 14 / 2 – 5*4 Last step is to evaluate subtraction 7-20=-13 After the side effects the variables have the values shown below a=2 b=4 c=6 Warning
97
Type Conversion (1 of 6) Implicit Type Conversion
Up to this point, we have assumed that all of our expressions involved data of the same type. But, what happens when we write an expression that involves two different data types, such as multiplying an integer and a floating-point number? To perform these evaluations, one of the types must be converted. Type conversion is of two types: Implicit Type Conversion Explicit Type Conversion (Cast) Implicit Type Conversion When the types of the two operands in a binary expression are different, C automatically converts one type to another. This is known as implicit type conversion. Conversion rank: We assign a rank to the integral and floating point arithmetic types. These ranks are known as conversion ranks. Conversion ranks are shown below
98
Type Conversion (2 of 6) Conversion Rank
Program for implicit type conversion u1_ex36.c
99
Type Conversion (3 of 6) Conversions in Assignment Expressions
A simple assignment involves an assignment operator and two operands. Depending on the difference in the rank, C tries to either promote or demote the right expression to make it the same rank as the left variable. Promotion occurs if the expression has lower rank. Demotion occurs if the right expression has higher rank. Promotion There is normally no problem with promotion. The rank of right expression is elevated to the rank of the left variable. The value of the expression is the value of the right expression after the promotion. Ex: bool b= true char c= ‘A’ int i=1234 long double d= c=b //value of c is SOH (ASCII 1) i= c //value of i is 65 d=b //value of d is is 1.0 d=i // value of d is
100
Type Conversion (4 of 6) Demotion
Demotion may or may not create problems. If the size of the variable at the left side can accommodate the value of the expression, then there is no problem. If the size of the variable at the left side can not accommodate the value of the expression, then demotion occurs. Ex: bool b = false char c = ‘A’ short int s = 78 int j = 32200 int k = 65 b=c // value of b is 1 (true) s=j // value of s is unpredictable c=k+1 // demotion value of c is ‘B’
101
Type Conversion (5 of 6) Conversion in other binary expressions
Conversion has a different set of rules for other binary expressions. The operand with higher rank is determined using the ranking table. The lower ranked operand is promoted to the rank defined in step 1. After the promotion both expressions have the same rank. The operation is performed with the expression value having the type of the promoted rank. Ex: bool b = true; char c = ‘A’ int i = 3650 short int s= 78 long double d = \ b + c // b promoted: result is ‘B’ I * s // result is an integer d * c // result is long double
102
Type Conversion (6 of 6) Explicit type conversion (cast)
In explicit type conversion we convert the data from one type to another type using explicit type conversion. Explicit type conversion uses the unary type cast operator To cast the data from one type to another, we specify the new type in parentheses before the value we want to convert. Ex: (float) a One use of the cast is to ensure that the result of a divide is a real number. Ex: avg=(float) totalscores/ numscore here totalscores is integer numscore is int but result is float due type cast operator before totalscores Program for explicit type conversion u1_ex37.c
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.