UNIT - 1jhjhjbkjhkjhkjhkjhkjhhkkhhh.pptx

RoselinLourd 28 views 178 slides Sep 22, 2024
Slide 1
Slide 1 of 178
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178

About This Presentation

nnkj


Slide Content

UNIT - 1 INTRODUCTION TO C

What is Programming and Languages? A programming language is a notation for writing programs, which are specifications of a computation or  algorithm A programming language is a set of rules that provides a way of telling a computer what operations to perform A programming language is a set of rules for communicating an algorithm Medium of communication between computer and the user containing words, symbols and syntax rules Each language has its own vocabulary and rules.

Generation of Programming Languages There are Five Generations of Programming languages 1 Machine Language (1st Generation Language – 1945 ) 2 Assembly Language(2nd Generation Language – 1950s ) 3 High Level Language (3rd Generation Language – 1960s ) 4 Very High Level Language (4th Generation Language – 1970s ) 5 Natural Language (5th Generation Language – 1980)

List of High Level Language FORTRAN - Formula Translation Language COBOL - Common Business Oriented Language ALGOL - Algorithmic Language RPG - Report Program Generator APL - A Programming Language BASIC - Beginners All Purpose Symbolic Instruction Code PL/I - Programming Language I PASCAL -Named after Blaise Pascal, a French Philosopher Ada - Named after Lady Lovelace Ada C - A General Purpose Programming Language C ++ Object Oriented Programming Language JAVA -Object Oriented Programming Language

Some examples of the use of C Programming 5 Operating Systems. Language Compilers. Assemblers. Text Editors. Print Spoolers. Network Drivers. Modern Programs. Data Bases. Hardware Internet Application Memory Management Firewalls Virus Protection Gaming S/W etc.,

History of C C  is a middle-level programming language developed by Dennis Ritchie during the early 1970s while working at AT&T Bell Labs in the USA. Eventually , C was developed during 1971-73, containing both high-level functionality and the detailed features required to program an operating system. C is a general-purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations , etc.

Why Should I learn C Programming C is a procedural programming language . The main features of C language include low-level access to memory , simple set of keywords, and clean style , these features make C language suitable for system programming like operating system or compiler development. 7

Why Should I learn C Programming Cont.. 1 . There are some good reasons to learn to program in C. First, The age has its advantages: C has been around for 30 years , and there is a ton of source code available in the field. 2. This means there's a lot to learn from, and a lot to use. Moreover, many of the issues with the language have been clearly elucidated 3. Plus, with C, you get lots of strong opinions mixed with insights that you can understand. 8

Why Should I learn C Programming Cont.. In fact, a lot of fun programming is done in C -- for instance, system software and data managers. If you want to be able to do more than write a simple web app , C is a great language. If you want to write a great, fast game , C is again a great choice. You can write an entire Operating System Software in C. 9

Benefits or Importance of C Language As a middle-level language , C combines the features of both high-level and low-level languages. C is a structured programming language which allows a complex program to be broken into simpler programs called functions. Various features of C including direct access to machine level hardware . C language an optimum choice for scripting applications and drivers of embedded systems . C language is case-sensitive which means lowercase and uppercase letters are treated differently. 10

Benefits or Importance of C Language C is highly portable and is used for scripting system applications which form a major part of Windows, UNIX, and Linux operating system. C is a general-purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations , etc. C language has a rich library which provides a number of built-in functions. C implements algorithms and data structures swiftly, facilitating faster computations in programs. like MATLAB and  Mathematica . 11

Structure of C Program Every C program contains a number of building blocks . These building blocks should be written in a correct order and procedure, to execute without any errors.

1. Documentation Section The general comments are included in this section. The comments are not a part of executable programs. The comments are placed between delimiters (/* and */). Example: //Factorial of a given number /* This program for factorial of a given number */

2. Preprocessor Section It provides preprocessor statements which direct the compiler to link functions from the system library. Example #include< stdio.h > #include< conio.h > # include< math.h > # include< string.h >

#include < stdio.h > printf (), scanf () #include< conio.h > clrscr (), getch () #include < math.h > pow (), sqrt () # include< string.h > strlen (), strcpy ()

3. Definition Section This section defines all symbolic constants . It refers to assigning macros of a name to a constant. Example #define PI 3.14 #define TRUE 1 #define FALSE 0

Global Declaration Section It contains variable declarations, which can be accessed anywhere within the program. It should declare before the main() function . Global variable otherwise known as External variable or Public variable. Example int a; main() { ------ ------ }

main() function Each and every C program should have only one main() function . Without main() function, the program cannot be executed. The main function should be written in lowercase only . It should not be terminated with semicolon .

Declaration Part Each and every variable should be declared before going to use those variables in execution part. Execution part Here, the logic of the program can be implemented. These statements are known as program statements or building blocks of a program. They provide instructions to the computer to perform a specific task .

Subprogram section The subprogram section contains all the user-defined functions that are called in the main() function. User-defined functions are generally placed immediately after the main() function , although they may appear in any order.

Example Program 1 #include< stdio.h > void main() { p rintf(“SMVEC”); } Output: SMVEC

Example Program 2 #include< stdio.h > v oid main() { i nt a,b,c ; printf (“Enter the value of a=”); s canf (“% d”,&a ); printf (“Enter the value of b=”); scanf (“% d ”,&b ); c = a+b ; p rintf (“Sum of a and b=% d”,c ); }

Example Program 3

Process of Compiling and running a C program

COMPILATION & LINKING PROCESSES Execution is the process of running the program, to execute a ‘c’ program, we need to follow the steps given below. 1. Creating the program 2. Compiling the program 3. Linking the program with system library. 4. Executing the program.

Sample.C Sample.obj Sample.exe Compiler Linker

Turbo C++ IDE

First C Program

Save the file with .c extension

SAMPLE.C

Compile the file using Alt+F9

Run the file using Ctrl+F9

IDE(I ntegrated D evelopment E nvironment ) An integrated development environment ( IDE ) is a software application that provides comprehensive facilities to computer programmers for software development. An  IDE  normally consists of at least a source code editor, build automation tools and a debugger.

IDE FOR C/C++ Visual Studio Code Eclipse NetBeans   Sublime Text Atom Code:: Blocks CodeLite CodeWarrior

Visual Studio code A visual studio code is a lightweight software application with a powerful source code editor that runs on the desktop . It is a free source code editor developed by Microsoft for  Windows , Mac OS and  Linux . It is a software editor that has a rich extension of various languages like  C++ , C+,  C ,  Java ,  Python ,  PHP ,  Go , etc. and runtime language extensions such as  .NET  and Unity . It is easy to edit, build, syntax highlighting, snippets, code refactoring and debugging. In visual studio code, we can change the application's background theme, keyboard shortcuts set on our preferences, install an extension and add additional functionality.

It is an open-source code editor developed by Microsoft for Windows, Linux and Mac OS. Visual Studio Code is based on an Electron framework

Visual Studio code Key Benefits: Support for Debugging Syntax highlighting Intelligent Code completion, snippets and code refactoring EmbeddedGit Control Completely portable Easy customization Programming Languages Supported:  C, C++, C#, CSS, Go, HTML, Java, JavaScript, Python, PHP, TypeScript and much more.

PROGRAM A program consists of a series of instructions that a computer processes to perform the required operation .

Characteristics of a program Accuracy Clarity Modularity Portability Flexibility Efficiency Generality Documentation

Program Development Life Cycle • Problem Definition • Problem Analysis • Algorithm Development • Coding & Documentation • Testing & Debugging • Maintenance

Programming languages Procedural programming (e.g. C , Fortran, Pascal) Object-oriented programming (e.g. C++, Java, Python) Functional programming (e.g. Lisp, ML, Haskell) Logic programming (e.g. Prolog)

PROBLEM SOLVING TECHNIQUES Problem solving technique is a set of techniques and graphical tools that help in providing logic for solving a problem . Some of the problem solving tools are 1. Algorithm 2. Flowchart 3. Pseudo code

Algorithm Algorithm means the logic of a program . It is a step-by-step description of how to arrive at a solution of a given problem .

C haracteristics of an algorithm In algorithms each and every instruction should be precise . In algorithms each and every instruction should be unambiguous . The instructions in an algorithm should not be repeated infinitely. Ensure that the algorithm will ultimately terminate . The algorithm should be written in sequence . It looks like normal English . The desired result should be obtained only after the algorithm terminates .

Algorithm for sum of two numbers

Flowchart Flowchart is a pictorial representation of an algorithm. It is often used by programmer as a program planning tool for organizing a sequence of step necessary to solve a problem by a computer.

Flowchart Symbols

Algorithm and Flowchart Sum of Two numbers

Data Name (or) Variable In C, a variable is a data name used for storing a data value . Its value may be changed during program execution. The value of variables keeps on changing during the execution of a program. In other words, a variable can be assigned different values at different times during the execution of a program.

Rules for naming the variables A variable name can be any combination of alphabets , digits or underscore . But first character should be alphabets or an underscore (_). The length of the variable cannot exceed up to 8 characters long. Some of the c compilers can be recognized up to 31 characters long. The variable should not be a C keyword . Both lowercase and uppercase are permitted. The special symbols are not permitted except underscore.

Syntax: datatype v1,v2,v3,…., vn ; Description: datatype - It is the type of data. v1, v2, v3 ,…, vn - list of variables. Example 1: int regno ; float cgpa ; char name[10];

Example 2: Declaration of multiple variables of the same data types can be done in one statement. int mark1; int mark2; int mark3; int mark4; can be written to become int mark1, mark2, mark3, mark4;

Two types: ✓ Local variables ✓ Global variables

Local variables: The variables which are defined inside a function block or inside a compound statement of a function sub- program are called local variables. #include< stdio.h > v oid main() { i nt i=10; ---- ---- }

Global variables : The variables that are declared before the function main() are called the global/external variables. int a=5; #include< stdio.h > void main() { Int i=10; ---- ---- }

Data Type Data type is the type of the data , that are going to access within the program. C supports different data types , each data may have predefined memory requirement and storage representation.

User defined data types Empty data set Primary data types Derived data types Data Types char int double float typedef enum array pointer union struct void

1. Primary data types C has the following basic built-in primary datatypes . • char • int • float • double

char (Character) Char (Character) data type is used to store single character , within single quotes e.g. 'a', 'z', 'e' etc. Syntax: char variablename ; Example: char chi='a', cha; int (Integer) Integer data type is used to store numeric values without any decimal point e.g. 7, -101 , 107, etc. Syntax : int variablename ; Example: int roll, marks, age; int marks=100;

float Float data type is used to store numeric values with decimal point. e.g. 3.14, 7.67 etc. e.g. percentage, price, pi, area etc. Syntax : float variable name; Example : float per, area; per=95.7; double Double is used to define BIG floating point numbers . It reserves twice the storage for the number. It contains 8 bytes . Syntax : double variablename ; Example : double Atoms;

Format Specifiers %d or %i – integer %c – character %f – float %s – string %e – double %o – octal %x - Hexadecimal

PROGRAM //primary data types #include< stdio.h > #include< conio.h > void main() { int rollno ; float fees; char grade; clrscr(); printf("\ tprimary data types\n"); printf("Enter rollno :\n"); scanf("%d",& rollno ); printf("Enter fees:\n"); scanf("% f",&fees ); printf("Enter grade:\n"); scanf ("% c ",& grade ); printf("The details are\n"); printf("Roll no=%d\n", rollno ); printf("Fees=%.2f\ n",fees ); printf("Grade=%c\ n",grade ); getch(); }

OUTPUT

2. User defined data type User defined data type is used to create new data types . Types: typedef enum

typedef : The ' typedef ' allows the user to define new data-types that are equivalent to existing data types . Syntax: typedef type new-type; Type refers to an existing data type. New-type refers to the new user-defined data type. Example: typedef int number; Declare integer variables as: number roll, age, marks; It is equivalent to: int roll, age, marks;

enum (Enumeration ) Enumeration types provide the facility to specify the possible values of a variable by meaningful symbolic means . Syntax: enum enumname {member1,member2 ,..., membern }; Example: enum colour { black,white,pink,red,green,yellow }; An enumeration type is implemented by associating the integer value with the enumeration constant. Thus , the value 0 is associated with black, 1 with white, 2 with pink, 3 with red, 4 with green, 5 with yellow.

3. Derived Data type Data types that are derived from fundamental data types are called derived data types. Types – array, pointer, structure and union. Array An array is a collection of variables of same type i.e. collection of homogeneous data referred by a common name . In memory, array elements are stored in a continuous location . Syntax: datatype arrayname [ ]; Example: int a[10]; char name[20 ];

p ointer A pointer is a special variable that holds a memory address of another variable . Syntax : datatype * var_name ; Example : int a,*b; b=&a; * - indirection operator & - address of operator variable 'b' stores the address of variable 'a'.

#include< stdio.h > v oid main() { int a,*b; a=10; b =&a; p rintf(“value of a=% d”,a ); p rintf(“address of a =% d ”,&a ); printf(“value of b=% d ”,b ); printf(“address of b=% d”,&b ); p rintf(“value of a through b=% d ”,*b); } 10 a -12 -12 b -14 Variable Value Address

output

Struct A struct is a user defined data type that stores multiple values of same or different data types under a single name . In memory, the entire structure variable is stored in sequence. Syntax: Example: struct <structure name> { member1; member2; ----- ----- }; Structure name is the name of structure. e.g. store details of a student as - name, roll, marks. struct student { char name [20]; int roll, float marks; };

union A union is a user defined data type that stores multiple values of same or different data types under a single name . In memory, union variables are stored in a common memory location . Syntax: Example: union <tag name> { var1; var2; ----- ---- }; Tag name is the name of union, e.g , store details of a student as- name, roll, marks. u nion student { char name[20 ]; int roll, float marks; };

Difference between Structure and Union

C Character Set The character set is the fundamental raw material of any language and they are used to represent information .

SOURCE CHARACTER SET

EXECUTION CHARACTER SET Escape Sequence Name Meaning \a Alert Sounds a beep \b Backspace Backs up 1 character \f Formfeed Starts a new screen of page \n New line Moves to beginning of next line \r Carriage return Moves to beginning of current line \t Horizontal tab Moves to next tab position \v Vertical tab Moves down a fixed amount \\ Back slash Prints a back slash \’ Single quotation Prints a single quotation \” Double quotation Prints a double quotation \? Question mark Prints a question mark

C TOKENS Keywords Identifiers Constants String Operators Special Symbols C Tokens Operators Constants Special Symbols String Identifiers Keywords

1. Keywords Keywords are C tokens that have a strict meaning. They are explicitly reserved and cannot be redefined. All keywords must be written in lowercase . All keywords have fixed meanings and these meanings cannot be changed. C has 32 key words. Some implementations such as Borland’s C or Microsoft’s C have additional key words .

List of Keywords auto do goto signed unsigned break double if sizeof void case else int static volatile char enum long struct while const extern register switch c ontinue float return typedef default for short union

2. Identifiers It is used to refer the name of the variables, functions and arrays . An identifier is a token: Composed of a sequence of letters , digits , and the underscore character _ Note: Variable names are identifiers

Rules An identifier must begin with a letter . Both upper case and lower cases are permitted. Keywords are not permitted . No special symbols are permitted except underscore (_). Some C compiler accept under score may appear in first letter . Maximum length of an identifier is 31 . Blank spaces are not allowed in between an identifier.

Example: Regno _ regno Reg no Regno4 5regno

3. Constants

Numeric constants There are two types of numeric constants, 1 . Integer constants Real or floating-point constants Integer constants • An integer constant refers to a sequence of digits without a decimal point. Example : marks 90, per 75 Real Constants A Real constant is made up of a sequence of numeric digits with presence of a decimal point . Example : distance =126.0; Height = 5.6;

Character Constants There are two types, they are given below. i ) Single Character constants ii ) String constants Single Character constants A single character constant is a single alphabet , a single digit or a single special symbol enclosed within single inverted commas . Example : ۥ m ۥ ۥ ۥ = ۥ A ۥ String constants A string constant is a sequence of characters enclosed in double Quotes , the characters may be letters, numbers, special characters and blank spaces etc. Example : ”hi”, “325”.

Importance of Input and Output function in C We feed information into the computer, tell the computer what do with it, and then get a result back out. The information we put into a computer is called  input  and The information we receive from the computer is called  output . Input can come from just about anywhere. Keystrokes on a keyboard , data from an internet connection, or sound waves converted to electrical signals are examples of input . Output can also take many forms such as video played on a monitor , a string of text displayed in a terminal, or data we save onto a hard drive. The collection of input and generation of output is known under the general term,  input/output , or  I/O  for short, and is a core function of computers.

Input and Output functions in C Interestingly, the C programming language doesn't have I/O abilities built into it. It does, however, provide us with an external library containing I/O functions which we can compile and link into our programs. We have already used an output library function:  printf () . You may recall this function resided in the  stdio.h  library file. As that file's name implies,  stdio.h  contains standardized I/O functions for adding input and output capability to our programs.

Input and Output functions in C – I/O Stream C has no built-in statements for input or output . All input and output is performed with streams . A " stream " is a sequence of characters organized into lines. Each line consists of zero or more characters and ends with the "newline" character.

I/O Stream All input and output is performed with streams , which are sequences of bytes. In input operations, the bytes flow from a device (e.g., a keyboard, a disk drive, a network connection) to main memory . In output operations, bytes flow from main memory to a device (e.g., a display screen, a printer, a disk drive, a network connection, and so on).

I/O Stream Normally, the standard input stream is connected to the keyboard and the standard output stream is connected to the screen . Operating systems often allow these streams to be redirected to other devices. A third stream, the standard error stream , is connected to the screen. Error messages are output to the standard error stream.

Types of Stream in C - Summary Standard input stream is called " stdin " and is normally connected to the keyboard Standard output stream is called " stdout " and is normally connected to the display screen. Standard error stream is called " stderr " and is also normally connected to the screen.

Input / Output data flow and assign A stream is an abstraction that refers to a flow of data. standard output device stdout variable a printf(”%d”,a); standard input device stdin variable a scanf(”%d”,&a); Keyboard Monitor

getc () and putc () getc ()  which reads the next available character from the screen. putc () which prints the character. Syntax: x= getc (); putc (); Example: char x; x= getc (); putc (x); Program: #include < stdio.h > void main( ) { int c; printf ( "Enter a value :"); c = getc ( ); printf( "\ nYou entered: "); putc ( c ); } Output: Enter a value : a You entered: a

getchar () and putchar () getchar ()   which reads the next available character from the screen. p utchar () which prints the character. Syntax: x= getchar (); putchar (x); Example: char x; x= getchar (); putchar (x); Program: #include < stdio.h > void main( ) { int c; printf ( "Enter a value :"); c = getchar ( ); printf ( "\ nYou entered: "); putchar ( c ); } Output: Enter a value : a You entered: a

gets() and puts() gets()   is used to read the string from the standard input device (keyboard) puts() is used to display a single character to standard output device. Syntax: gets( dataname ); puts( dataname ); Example: char name[10]; gets(name ); puts(name); Program: #include< stdio.h > void main() { char name[100]; printf("Enter a string"); gets( name ); printf(“You entered:”) puts( name ); } Output: Enter a string : rahul You entered: rahul

scanf() and printf() The standard input-output header file, named  stdio.h  contains the definition of the functions  printf()  and  scanf() , which are used to display output on screen and to take input from user respectively . Program: # include< stdio.h > void main() { int i; printf ("Please enter a value:"); scanf ("%d", &i); printf ( "\ nYou entered: %d", i); } Output: Please enter a value: 10 You entered: 10

Scanf() with multiple input with Same data type void main () { int m1,m2,m3; printf(“Enter 3 marks for m1,m2,m3:”); scanf (“% d %d %d ”,&m1,&m2,&m3); printf(“\ nThe given Marks : %d %d %d”,m1,m2,m3); } output: Enter 3 marks for m1,m2,m3 : 67 87 95 The given Marks : 67 87 95

void main() { int age float per; printf (“Enter your age and percentage:”); scanf (“%d %f” ,& age,&per ); printf(“\ nMy age is %d and percentage is:% f,age,per ); } output: Enter your age and percentage : 18 85.26 My age is 18 and percentage is: 85.26 Scanf() with multiple input with different data type

Operators and Operands Operators are symbols that instruct the computer to perform a single, simple task, and most consist of just one or two characters ( =, +, *, <=, or == -), but some operators consist of a complete word ( sizeof ()). Operands are expressions or values on which an operator operates or works (often constants or variables but sub-expressions are also permitted).

Operand examples : In each example,  +   is a  operator  while the symbols appearing on either side of it are  operands . Operands may be constants 2 + 5 Operands may be variables A + B Operands may be more complex expressions 2*A + 5*B

Number of Operands Operators are characterized by the number of operands that they require. Most operators require one or two operands but C does have one operator that requires three. Unary Operators Unary operators only require one operand. Most of the time the operand is placed to the right of the operator but sometimes it is placed to the left. The most common example is the unary minus: ‑N, which changes the sign of the value stored in variable N. Binary Operators Binary operators require two operands. The arithmetic operators are the most familiar examples of binary operators. The assignment operator is also common. For example: A = counter + 5; "counter" and "5" are the "+" operator's operands, and "A" and the value of the expression "counter + 5" are the "=" operator's operands. Note that the above example ends with a semicolon, which also makes it an example of a statement (specifically, an assignment statement).

Arithmetic Expressions: Design Issues 1- 109 Design issues for arithmetic expressions operator precedence rules operator associativity rules order of operand evaluation operand evaluation side effects mode mixing expressions

Arithmetic Expressions: Operators 1- 110 A unary operator has one operand A binary operator has two operands A ternary operator has three operands

Order of Operator Evaluation All operators have two characteristics that effect the order in which they are evaluated: precedence and associativity . The rules that establish these characteristics are either based on similar properties from algebra or follow the best practices that have evolved over decades of programming language development.

Operator Precedence Rules 1- 112 The operator precedence rules for expression evaluation define the order in which “adjacent” operators of different precedence levels are evaluated

113 Structure of Arithmetic Expressions For example : a + b - c * d / e % f - a + b - c * d / e % f – (398 + g) * 5981 / 15 % h ((- a) + b - c) * d / e % f – ((398 + g) * 5981 / 15) % h

114 Structure of Arithmetic Expressions Putting a term in parentheses may change the value of the expression, because a term inside parentheses will be calculated first . For example: a + b * c is evaluated as “multiply b by c, then add a ,” but (a + b) * c is evaluated as “add a and b , then multiply by c ”

Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e 4 3 2 a + b * c - d / e 3 2 4 1 a / (b + c) - d % e 2 3 4 1 a / (b * (c + (d - e))) 4 1 2 3 1

Assignment Revisited You can consider assignment as an operator, with a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated Then the result is stored in the variable on the left hand side answer = sum / 4 + MAX * lowest; 1 4 3 2

Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count Then the result is stored back into count (overwriting the original value) count = count + 1;

119 Precedence Order Examples 1 - 2 - 3 = 1 - (2 - 3) = 1 + 2 * 3 + 4 = 1 + 2) * 3 + 4 = 24 / 2 * 4 = 24 / (2 * 4) = 5 + 4 % 6 / 2 = 5 + 4 % (6 / 2) = 5 + 4) % (6 / 2) =

Precedence and Order of evaluation

ASCII ASCII, abbreviated from American Standard Code for Information Interchange , is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other device.

Type Conversion (or) Type casting A type cast is basically a conversion from one type to another . There are two types of type conversion : Implicit type conversion Done by the compiler on its own Explicit type conversion Done by the user

#include<stdio.h> int main() { int x = 10; char y = 'a'; // y implicitly converted to int. ASCII // value of 'a' is 97 x = x + y; // x is implicitly converted to float float z = x + 1.0; printf ("x = %d, z = %f", x, z); return 0; } Output: x = 107, z = 108.000000

Type Conversion Explicit type conversion Converted by programmer using cast operator ( type name) expression ; x=(int)7.5 y=(int) ( a+b ) m=(23*2)%(int)5.4

#include<stdio.h> int main() { double x = 1.2; // Explicit conversion from double to int int sum = (int)x + 1; printf ("sum = %d", sum); return 0; }

129 What is an Expression? a + b - c * d / e % f – (398 + g) * 5981 / 15 % h In programming, an expression is a combination of: Operands Operators Parentheses : ( ) Eg : C= a+b ; C,a,b =operands =,+: operators

Operators are Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Special operators

Arithmetic Operators An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).

Types of operator Symbolic Representation Arithmetic operator +,-,*,/ and % Relational operator >,<,==,>=,<= and != Logical operator &&,|| and ! Increment and decrement operator ++ and -- Assignment operator = Bitwise operator &,|,^,>>,<< and ~ Comma operator , Conditional Operator ?:

CO2. To gain knowledge about the control structures in C Arithmetic operators Operator Meaning + Addition or Unary Plus – Subtraction or Unary Minus * Multiplication / Division % Modulus Operator

CO2. To gain knowledge about the control structures in C Integer Arithmetic Let x = 27 and y = 5 z = x + y  32 z = x – y  22 z = x * y  115 z = x / y  5 z = x % y  2 Q:5 R:2

CO2. To gain knowledge about the control structures in C Floating point arithmetic Let x = 14.0 and y = 4.0 then z = x + y  18.0 z = x – y  10.0 z = x * y  56.0 z = x / y  3.50 The operator % cannot be used with FLOAT operands

Mixed mode Arithmetic When one of the operand is real and the other is integer then the result is also real and the operation is called mixed mode arithmetic. Eg : 15/10.0= 1.5

Relational Operators Relational Operators: Compare two quantities and depending on their relation taken certain decision. <, <=, > >=, ==, != are the relational operators. Relational operators are used in decision making and loops. 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.

CO2. To gain knowledge about the control structures in C Relational Expressions 6.5 <= 25 TRUE -65 > 0 FALSE 10 < 7 + 5 TRUE

CO2. To gain knowledge about the control structures in C Relational Operators 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

Logical Operators Logical Operators: Used to test more than one condition and make decisions. Logical operators are commonly used in decision making in C programming. &&, || and ! are the three logical operators. expr1 && expr2 has a value 1 if expr1 and expr2 both are nonzer o. 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 = ‘F’ AND 0*0=0 0*1=0 1*0=0 1*1=1 OR 0+0=0 0+1=1 1+0=1 1+1=1

CO2. To gain knowledge about the control structures in C Find out the answer a = 5 b = 4 x=10, y = 9 m=6 n = 3 a > b && x = = 10 True / 1 a < m || a < n True / 1 ! (x >= y) False / 0

Assignment Operators Assignment operators: Assigning the result of an expression to a variable. An assignment operator is used for assigning a value to a variable. The most common assignment operator is =. The general form of an assignment operator is v op= exp Where v is a variable and op is a binary arithmetic operator. This statement is equivalent to v = v op (exp) a = a + b can be written as a += b a = a * b can be written as a *= b a = a / b can be written as a /= b a = a - b can be written as a -= b a = a*(n+1) can be written as a*=n+1

CO2. To gain knowledge about the control structures in C 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

CO2. To gain knowledge about the control structures in C 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

Unary Operators Unary operators act on single operands. C language supports three unary operators. They are unary minus, increment, and decrement operators. Unary Minus (–) Unary minus operator negates the value of its operand. For example, if a number is positive then it becomes negative when preceded with a unary minus operator. Similarly, if the number is negative, it becomes positive after applying the unary minus operator. For example, int a, b = 10; a = –(b); The result of this expression is a = –10, because variable b has a positive value. After applying unary minus operator (–) on the operand b, the value becomes –10, which indicates it has a negative value.

C Increment and Decrement Operators C programming has two operators increment ++ and decrement - - to change the value of an operand (constant or variable) by 1. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand . A=10 A + b ; binary ++ a; unary 11 -- a ; unary 9

Increment and Decrement Operators Increment and Decrement Operators The operators ++ and –- are called increment and decrement operators . Post Increment: a++ Pre increment: ++a a ++ = a=a+1 a -- = a=a-1 Example Let a = 10 a++ =10 ++a= 11 (++b)+ b+b = 33 b+(++b)+b = 33 b+b +(++b) = 31 b+b *(++b) = 132 Post decrement: a-- Pre decrement: --a

Rules for increment and decrement Increment and decrement operators are unary operators and thus require variable as their operands. When postfix ++ or – is used with a variable in an expression , the expression evaluated first using the original value of the variable and then the variable is incremented (or decremented) by one. When prefix ++ or – is used in an expression , the variable is incremented first then the expression is evaluated using the new value of the variable. The precedence and associativity of ++ and – operators are the same as those of unary + and unary -.

Increment and Decrement Operators m = 5; y = ++m; (prefix) After Execution: y=6, m=6 m = 5; y = m++; (post fix) After Execution: y=5, m=6

Conditional Operators Conditional Operator: The conditional operator contains a condition followed by two statements or values. If the condition is true the first statement is executed , otherwise the second statement . A ternary operator pair” ? : “ is available in to construct conditional expressions of the following form: condition ? exp1: exp2 where exp1, exp2, exp3 are expressions. Eg : a=10; b=15; x=(a>b) ? a : b; if the condition is true a part will be executed else b part will be executed.

C Bitwise Operators During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power. Bitwise operators are used in C programming to perform bit-level operations

Operators Bitwise Operator To manipulate data at bit level, used for testing the bits, or shifting them right to left. They not be applied to float or double. Operator meaning & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR << Shift left >> Shift right

12 & 25=8

Bitwise XOR Operator Same = > zero Diff => one

~n=-(n+1) ~35=-(35+1)=-36

CO2. To gain knowledge about the control structures in C Special Operators comma operator int a,b,c ; size of operator sifeof (a);=>2 pointer operators (& and *) member selection operators (. and ->). structure

CO2. To gain knowledge about the control structures in C The Comma Operator value = (x = 10, y = 5, x + y); In for loops: for (n=1, m=10, n <=m; n++,m++) In while loops While (c= getchar (), c != ‘1’) Exchanging values t = x, x = y, y = t;

Comma Operator Comma operators are used to link related expressions together. For example: int a, c = 5, d;

The sizeof operator The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc ).

P ointer operators & Returns the address of a variable. &a; returns the actual address of the variable. * Pointer to a variable. *a;

dot (.) operator The dot (.) operator is used for direct member selection via object name. In other words, it is used to access the child object. It is used in Structure and Union. Syntax: object.member ;

An Arrow operator in C allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below. Syntax: ( pointer_name )->( variable_name ) Operation: The -> operator in C gives the value held by variable_name to structure or union variable pointer_name .

Difference between Dot(.) and Arrow(->) operator The Dot(.) operator is used to normally access members of a structure or union . The Arrow(->) operator exists to access the members of the structure or the unions using pointers .
Tags