History of C. Introduction to C. Why are using C

Similar documents
C Programming Class I

Fundamental of Programming (C)

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

UNIT- 3 Introduction to C++

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

C - Basic Introduction

Fundamental of C programming. - Ompal Singh

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Basics of Programming

Data Types and Variables in C language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

DEPARTMENT OF MATHS, MJ COLLEGE

Fundamentals of Programming

C: How to Program. Week /Mar/05

Chapter 1 & 2 Introduction to C Language

UNIT IV INTRODUCTION TO C

Chapter 2 - Introduction to C Programming

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

ANSI C Programming Simple Programs

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

C Programming Multiple. Choice

Computers Programming Course 5. Iulian Năstac

Operators and Expressions:

Work relative to other classes

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS)

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

The component base of C language. Nguyễn Dũng Faculty of IT Hue College of Science

INTRODUCTION 1 AND REVIEW

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities

Basic Elements of C. Staff Incharge: S.Sasirekha

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Java Notes. 10th ICSE. Saravanan Ganesh

I BCA[ ] SEMESTER I CORE: C PROGRAMMING - 106A Multiple Choice Questions.

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Programming and Data Structures

Preview from Notesale.co.uk Page 6 of 52

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Operators. Java operators are classified into three categories:

UNIT 3 OPERATORS. [Marks- 12]

BCA-105 C Language What is C? History of C

4.1. Structured program development Overview of C language

Computer System and programming in C

FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING UNIT IV INTRODUCTION TO C

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

C++ character set Letters:- A-Z, a-z Digits:- 0 to 9 Special Symbols:- space + - / ( ) [ ] =! = < >, $ # ; :? & White Spaces:- Blank Space, Horizontal

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

C Language, Token, Keywords, Constant, variable

Presented By : Gaurav Juneja

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Full file at C How to Program, 6/e Multiple Choice Test Bank

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

KARMAYOGI ENGINEERING COLLEGE, Shelve Pandharpur

A Fast Review of C Essentials Part I

MODULE 2: Branching and Looping

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Data types, variables, constants

UNIT-2 Introduction to C++

Lecture 02 C FUNDAMENTALS

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

CSCI 171 Chapter Outlines

Introduction to C. History of C:

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

6.096 Introduction to C++ January (IAP) 2009

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

THE FUNDAMENTAL DATA TYPES

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Course Outline Introduction to C-Programming

Department of Computer Applications

The C++ Language. Arizona State University 1

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

PESIT Bangalore South Campus Hosur Road (1km before Electronic City), Bengaluru Department of Basic Science and Humanities

More Programming Constructs -- Introduction

Computers Programming Course 6. Iulian Năstac

LEXICAL 2 CONVENTIONS

SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

COMPONENTS OF A COMPUTER

UIC. C Programming Primer. Bharathidasan University

Multiple Choice Questions ( 1 mark)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Data Types and Variables in C language

Differentiate Between Keywords and Identifiers

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Chapter 2: Basic Elements of C++

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Programming for Engineers Introduction to C

Unit 3. Operators. School of Science and Technology INTRODUCTION

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

Computers Programming Course 7. Iulian Năstac

Have the same meaning as variables in algebra Single alphabetic character Each variable needs an identifier that distinguishes it from the others a =

JAVA Programming Fundamentals

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Unit 3 Decision making, Looping and Arrays

Transcription:

Introduction to C Generation of C Language 1. In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) 2. In 1970, Ken Thompson created a language using many features of BCPL and called it simply B. 3. In 1972, C is Introduced by Dennis Ritchie at Bell laboratories and in the UNIX operating system. 1960 1967 1970 1972 History of C ALGOL International Group BCPL Martin Richards B Ken Thompson Traditional C Dennits Ritchie 1978 K & R C Kernighan and Ritchie 1989 ANSI C ANSI Committee 1990 ANSI / ISO C ISO Committee 1 2 Why are using C It is a Structured Programming Language High Level Language Machine Independent Language It allows software developers to develop programs without worrying about the hardwareplatforms where they will be implemented TYPES OF C COMPILER 1. Borland C Compiler 2. Turbo C Compiler 3. Microsoft C Compiler 4. ANCI C Compiler 3 Characteristics of C Small size Extensive use of function calls Loose typing -- unlike PASCAL Structured language Low level (Bitwise) programming readily available Pointer implementation - extensive use of pointers for memory, array, structures and functions. Portability Flexibility C has now become a widely used professional language for various reasons. It has high-level constructs. It can handle low-level activities. It produces efficient programs. It can be compiled on a variety of computers. 4 1

Steps in Learning C Character set Files Data Structures C S Program Structure Documentation section Preprocessor section Constants, variable And Data types Control statements Functions Structures and Unions Pointers Arrays Algorithms Programs Definition section Global declaration section main() Declaration part; Executable part; 5 Sub program section Body of the subprogram 6 C s Character set C Character set Source Character set C TOKENS C TOKENS Alphabets A to Z & a to z Constants Strings Digits 0 to 9 Special Characters +,-,<,>,@,&,$,#,! Identifiers main amount -15.5 100 ABC YEAR Operators + - * / Execution Character set Escape Sequences \a,\b,\t,\n 7 Keywords float while Special Symbols [ ] 8 2

C s Identifiers Program elements where Identifiers are used Variables Functions C s keyword Basic Building Block of the Program This are the Reserved words This word s cant be changed 38 Keywords are used in the C Language Arrays Function parameters C keywords Macrosand macroparameters Type definitions Rules for Using Identifiers Only Letter, Digits and Underscore(_) 1 st character should be letter or _ Both Upper/lower case can be used It can be of any length No space and Special symbol is used It cant be a keyword 9 auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while 10 Data Types This are the type of the data that are going to access within the program. C s Data Type Primary User defined Derived Empty char int float double long double typedef Arrays Pointers Structures union void C s Data types cont. The primary data types are further classified as below. Integers are the whole numbers, both positive and negative. Integer Int (%d) 2 bytes,-32768 to 32767 Signed Short int (% d) 1 bytes, -128 to 127 Long int (% ld) 4 bytes, -2,147,483,648 to 2,147,483,647 Unsigned 11 Unsigned Int (% d) 2 bytes, 0 TO 65, 535 Unsigned shot int (%d) 1 bytes, 0 TO 255 Unsigned Long int (%ld) 4 bytes, 12 0 TO 4,294,967,295 3

C s Data types cont. Float are the numbers which contain fractional parts, both Positive and Negative. Float Type C s Data types cont. Char are the characters which contain alpha-numeric character. Characters are usually stored in 8 bits (one byte) of internal storage Character Type Float (%f or %g) 4 bytes, 3.4E -38 to 3.4E +38 Char (%c) 1 bytes, -128 to 127 Double (%lf) 8 bytes, 1.7E -308 to 1.7E +308 Long Double (%lf) 10 bytes, 3.4E -4932 to 1.1E+4932 The void is the Null Data type. Signed Char (%c) 1 bytes, -128 to 127 Unsigned Char (%c) 1 bytes, 0 to 255 13 14 C s Variables A variable is a data name as well as identifier that may be used to store a data value. Rules for Naming the Variables a) A variable can be of any combination of alphabets, digits and underscore. b) The first character of the variable can t be digits. c) The length of the variable can t be exceeded by 8.(ANSI C 32 Character) d) No commas, blanks or special symbol are allowed within a variable name. e) Uppercase and lowercase are significant. That is, the variable Total is not the same as total or TOTAL. f) It should not be a keyword. g) White space is not allowed. 15 C s Variables cont. Variable Declaration It tells the computer what the variable name and type of the data Syntax Description Example data_type a1,a2,a3..an; data_type is the type of the data. a1,a2,a3 an are the list of variables int number; char alpha; float price; Initializing Variables Initialization of variables can be done using assignment operator(=) Syntax Description a1 = c1 ;(or) data_type a1 = c1; a1 is the variable c1 is the constant data_type is the type of the data Example int a1 = 29; float f1 = 34.45; char c1 = d 16 4

C s constant The item whose values can t be changed during execution of program are called constants C constant C s constant Conti Integer constant eg: roll_number = 12345; Real Constant eg: pi = 3.14; Numeric constant Decimal Constant Eg. 35 Octal constant Eg. 043 Hexadecimal constant Eg. 0x23 Integer constant eg: roll_number = 12345; Real constant eg: pi = 3.14; Character constant Single Precision Constant Double Precision Constant Single Character constant eg: ch = c ; ch = 3 ; String constant eg: name = palani 17 18 Rules for constructing Integer constants 1. An integer constant may be positive or negative (Default sign is positive). 2. An integer constant should not have a decimal point. 3. No commas and blank spaces are allowed in an integer constant. 4. An integer constant, should not use exponent e. The suffix u or U is used for denoting unsigned int constants, I or L is used for denoting long int constants, and s is used for denoting short int constants. Positive integer Constants 123 4000 +7257 Negative integer Constants -78-9876 -23 Unsigned integer Constants 1234u 5678u 21057u Short integer Constants -5008s -23s 1234s Long integer Constant -40880211 0210578L 0x52123L Unsigned short integer Constants 1234us 5008us 8476us Unsigned long integer Constants 1234567890ul 9876543210ul 19 Real Constants are often called as Floating point constants. Real constants is classified as two types. 1. Fractional form. 2. Exponential form. Rules for constructing real constants (fractional form) 1. A real constant may be positive or negative (Default sign in positive 2. A real constant must have a decimal point. 3. No commas and blank spaces are allowed in a real constant. Example: 0.0001-0.963 485.98 +123.456 727.01 0.987 -.8765 +001.05 Rules for constructing Real Constants (Exponential Form) 1. The mantissa part and the exponential part should be separated by a letter e. 2. The mantissa part and the exponential part may be positive or negative (Default sign is positive) 3. The mantissa and the exponent part must have at least one digit. 4. No commas and blank spaces are allowed in a real constant. Example: +3.2e+5 3.4e5-8.2e-5 20-10.9e5 9.7e-10 0.0025e8 5

Rules for constructing String Constants 1. A string constant may be a single alphabet or a digit, or a special character or sequence of alphabets or digits enclosed in double quotes. 2. Every string constant ends up with a NULL character, which is automatically assigned. Example: w 100 Madhu ABC 123 Good_Morning s1000 219.71 30-01-1978 C Delimiters Delimiters are the symbols, which has some syntactic meaning and has got significance. C Statements Statement can be defined as set of declarations (or) sequence of action All statements in C ends with semicolon(;) except condition and control statement Statements Symbol Name Meaning # Hash Pre-processor directive, comma Variable delimiters (to separate list of variables) : colon Label delimiters ; Semi colon Statement delimiters () parenthesis Used in expressions or in functions Curly braces Used in blocking C structure [] Square braces Used along with arrays 21 Expression Statement Compound Statement Control Statement 22 C Statements Expression Statement Assignment statement name = palani ; number = 12; Sex = m ; Statements Null statement ; 23 1. An Expression is a combination of constant, variables, operators, and function calls written in any form as per the syntax of the C language. 2. The values evaluated in these expressions can be stored in variables and used as a part for evaluating larger expressions. 3. They are evaluated using an assignment statement of the form. variable = expression; 4. For Example, age = 21; result = pow(2,2); simple_interest = (p * n * r) / 100; Algebraic Expression (mnp + qr at) (a+b+c) (x+y+z) abc / x+y 8a 3 + 3a 2 + 2 a (a-b)+(x-y) / mn 8.8(a+b-c) + c / pq Equivalent C Expression (m*n* p+q*r-s*t) (a+b+c)*(x+y+z) (a*b*c) / (x+y) 8*a*a*a+3*a*a+2*a ((a-b)+(x-y)) / (m*n) 8.8 * (a+b-c) + (c / (p*q)) 24 6

Compound Statements 1. A group of valid C expression statements placed within an opening flower brace and closing flower brace is referred as a Compound Statements. 2. For Example, X = (A + (B * 3) C); Y = A + B * 3; Z = A * (B * 3 C); Control Statements 1. This statement normally executed sequentially as they appear in the program. 2. In some situations where we may have to change the order of execution of statements until some specified conditions are met. 3. The control statement alter the execution of statements depending upon the conditions specified inside the parenthesis. 4. For Example, if (a == b) if ((x < y) && (y > z)) -------- ----------- -------- ----------- 25 ESCAPE SEQUENTIAL CHARACTER OR BACKSLASH CHARACTER CONSTANTS Constant \a \b \f \n \r \t \v Meaning Audible alert (bell) Back space Form feed New line Carriage return Horizontal tab Vertical tab \ Single quote \ Double quote \? Question mark \\ Backslash \0 Null 26 Operators An operator is a symbol that specifies an operation to be performed on the operands Some operator needs two operands (binary) Eg: a+b; + is an operator and a and b are the operands Some operator needs one operand (unary) Eg: ++a; ++ is an operator and a is the operand Types of Operators operators Arithmetic operator Relational operators Logical operator Assignment operator Increment and Decrement Operator (Unary Op.) Conditional operator (Ternary operator) Bitwise operator 27 Special operator 28 7

Arithmetic Operators This operators help us to carryout basic arithmetic operations such addition, subtraction, multiplication, division Operator Meaning Examples + Addition 1+2 = 3 - Subtraction 3-2 = 1 * Multiplication 2*2 = 4 / Division 2/2 = 1 % Modulo division 10/3= 1 Types of mode of Arithmetic Operator 1. Integer Arithmetic Operator 2. Real Arithmetic Operator 3. Mixed Mode Arithmetic Operator a % b equivalent to a ( a / b ) * b -14 % 3 = -2-14 % -3 = -2-14 % -3 = 2 Operation Result Examples int/int int 2/2 = 1 real/int real 7.0/2 = 3.5 int/real real 7/2.0 = 3.5 real/real real 7.0/2.0 = 3.5 29 Relational Operator This are used to compare two or more operands. Operands can be variables, constants or expression. eg: comparison of two marks or two values. Operator Meaning Example Return value < is less than 5<6 1 <= is less than or equal to 4<=4 1 > is greater than 5>7 0 >= is greater than or equal to 7>=5 0 == equal to 6==6 1!= not equal to 5!=5 0 30 Logical Operator This operatorsare used to combine the results of two or more conditions. Operator Meaning Example Return value && Logical And (9>2) && (6>4) 1 Logical OR (9>2) (3.4) 1! Logical Not 4! 4 0 AND truth table True True True True False False False True False False False False OR truth table True True True True False True False True True False False False 31 Assignment Operator This are used to assign a value or an expression or a variable to another variable eg: a = 10; n1 = 20; Syntax: a) Compound Assignment (b) identifier = expression; This operator are used to assign a value to a variable in order to assign a new value to a variable after performing a specified operation. eg: a+=10,n1-=20; += -> is Short hand Assignment Operator Advantages: (i) What appears on the left hand side need not be repeated and therefore it becomes easier to write. (ii) The statement is more concise and easier to read. (iii) The use of shorthand operatorsresults in a more efficient code. Nested Assignment (Multiple) This operator are used to assign a single value to multiple variables eg: a=b=c=d=e=10; 32 8

List of Shorthand or Compound Assignment Operator Operator Meaning += Assign Sum -= Assign Difference *= Assign Product /= Assign Quotient %= Assign Remainder ~= Assign One s Complement <<= Assign Left Shift >>= Assign Right Shift &= Assign Bitwise AND!= Assign Bitwise OR ^= Assign Bitwise X - OR Increment and Decrement operator C provide two operator for incrementing a value or decrementing a value a) ++ Increment operator (adds one to the variable) b) -- Decrement operator (Minus one to the variable) eg: a++ (if a= 10 then the output would be 11) Operator Meaning ++X Pre increment X++ Post increment --X Pre decrement X-- Post decrement 33 34 Increment and Decrement operator Conti If the value of the operand x is 3 then the various expressions and their results are Expression Result + + X 4 X + + 3 - - X 2 X - - 3 The pre increment operation (++X) increments x by 1 and then assign the value to x. The post increment operation (X++) assigns the value to x and then increments 1. The predecrement operation ( --X) decrements 1 and then assigns to x. The post decrement operation (x--) assigns the value to x and then decrements 1. These operators are usually very efficient, but causes confusion if your try to use too many evaluations in a single statement. 35 Conditional Operator It is used check the condition and execute the statement depending upon the condition Syntax Description Condition?exp1:exp2 The? operator act as ternary operator, it first evaluate the condition, if it is true then exp1 is evaluated if the condition is false then exp2 is evaluated Example a= 2; b=3 Bitwise Operator ans = a>b?a:b; printf (ans); This are used to manipulate the data at bit level It operates only on integers Operator & Meaning Bitwise AND Bitwise OR ^ Bitwise XOR << Shift left >> Shift right ~ One s complement 36 9

Bitwise Operator cont. The truth table for Bitwise AND,OR and XOR Bitwise AND (both the operand should be high for 1) 0 0 0 1 1 1 Bitwise OR (either of the operand should be high for 1) 0 0 0 1 1 1 Bitwise XOR (the two operands should be different for 1) 0 0 1 1 1 0 Eg: x = 3 = 0000 0011 y = 4 = 0000 0100 x&y = 0000 0000 Eg: x = 3 = 0000 0011 y = 4 = 0000 0100 x y = 0000 0111 Eg: x = 3 = 0000 0011 y = 4 = 0000 0100 x ^ y = 0000 0111 37 Bitwise Operator cont. Bitwise One s Complement The one s complement operator (~) is a unary operator, which causes the bits of the operand to be inverted (i.e., one s becomes zero s and zero s become one s) For Example, if x = 7 i.e 8 bit binary digit is 0 0 0 0 0 1 1 1 The One s Complement is 1 1 1 1 1 0 0 0 Bitwise Left Shift Operator The Left shift operator (<<) shifts each bit of the operand to its Left. The general form or the syntax of Left shift operator is variable << no. of bits positions if x = 7 (i.e., 0 0 0 0 0 1 1 1) the value of y in the expression y = x <<1 is 14 0 0 0 0 1 1 1 0 = 14 since it shifts the bit position to its left by one bit. The value stored in x is multiplied by 2 N (where n is the no of bit positions) to get the required value. For example, if x = 7 the result of the expression y = x << 2 is y = x * 2 2 (i.e. 28) 38 Bitwise Operator cont. Bitwise Left Shift Operator The Right shift operator (>>) shifts each bit of the operand to its Right. The general formor the syntax of Right shift operator is variable >> no. of bits positions if x = 7 (i.e., 0 0 0 0 0 1 1 1) the value of y in the expression y = x >> 1 is 3 0 0 0 0 0 0 1 1 = 3 since it shifts the bit position to its right by one bit. The value stored in x is divided by 2 N (where n is the no of bit positions) to get the required value. For example, if x = 7 the result of the expression y = x << 2 is y = x / 2 2 (i.e. 1). If you use the left shift operator i.e. x = x << 1 the value of x will be equal to 2 (i.e., 0 0 0 0 0 0 1 0) since the lost bit cannot be taken back. 39 Special Operator Some of the special operators used in C language. These operators are referred as separators or punctuators. 1. Ampersand (&) 2. Comma (,) 3. Asterisk ( * ) 4. Ellipsis ( ) 5. Braces () 6. Hash (#) 7. Brackets ([]) 8. Parenthesis (()) 9. Colon (:) 10. Semicolon(;) Operator Meaning Ampersand (&) Ampersand (&) also referred as address operator usually precedes the identifier name, which indicates the memory location (Address)of the identifier. Asterisk ( * ) Asterisk ( * ) also referred as an indirection operator, is an unary operator usally precedestheidentifiername, whichindicatesthe creationofa pointeroperator. Braces ( ) The opening ( ) and closing ( ) braces indicate the start and end of compound statement or a function. A semicolon is not necessary after the closing brace of the statement, exceptin case ofstructuredeclaration. Brackets ( [ ] ) Brackets [ ] also referred as array subscript operator is used to indicate single 40 and multi dimensional array subscripts. 10

Special Operator Operator Colon ( : ) Special Operator Colon ( : ) is used in labels. Meaning 41 Comma (, ) Ellipsis (...) Hash ( # ) Comma (, ) operator is used to link the related expressions together. Comma used expressions are linked from left to right and the value of the right most expression is the value of the combined expression. The commaoperatorhas the lowestprecedenceofall operators. For Example: sum = (x = 5, y = 3, x + y); The result will be sum = 8 Ellipsis ( ) are three successive periods with no white space in between them. It is used in function prototypes to indicate that this function can haveany numberof arguments withvaryingtypes. For Example: void fun(charcname, intiage, floatfsalary,...); The above declaration indicates that fun () is a function that takes at least three arguments, a char, an int and a float in the order specifiedbutcanhaveany numberof additionalargumentsofany type. Hash ( # ) also referred as pound sign is used to indicate preprocessor 42 directives. Operator Special Operator Meaning Parenthesis ( () ) Semicolon ( ; ) Sizeof ( ) Parenthesis ( ) also referred as function call operator is used to indicate the opening and closing of function prototypes, function calls, function parameters, etc., Parenthesis are also used to group expressions, and there by changingtheorder of evaluationofexpressions. Semicolon ( ; ) is a statement terminator. It is used to end a C statement. All valid C statements must end with a semicolon. Which the C compiler interprets as the end of the statement. The sizeof operator is not a library function but a keyword, which returns the size of the operand in bytes. The sizeof operator always, precedes its operand. This operator can be used for dynamic memory allocation. Example: 1. sizeof(char) = 1 2. sizeof(int) = 2 3. sizeof(float) = 4 Operator Precedence and Associativity of Operator 4. sizeof(doubles) = 8 43 44 11

What is Precedence Rule and Associative Rule 1. Each operator in C has a precedence associated with it. 2. This precedence is used to determine how an expression involving more than one operator is evaluated. 3. These are distinct levels of precedence and an operator may belong to one of these levels. 4. The operators at the higher level of precedence are evaluated first. 5. The operators of the same precedence are evaluated either from left to right or from right to left, depending on the level. 6. That is known as the associativity property of an operator. Arithmetic operators precedence The precedence of an operator gives the order in which operators are applied in expressions: the highest precedence operator is applied first, followed by the next highest, and so on. eg: Arithmetic operator precedence Precedence operator High *,/,% Low +,- 45 The arithmetic expression evaluation is carried out using two phases from left to right through the expressions 46 Example: if (x == 10 +15 && y <10) The precedence rules say that the addition operator has a higher priority than the logical operator (&&) and the relational operators (== and <). Therefore, the addition of 10 and 15 is executed first. This is equivalent to: if (x == 25 && y < 10) The next step is to determine whether x is equal to 25 and y is less than 10, if we assume a value of 20 for x and 5 for y, then x == 25 is FALSE (0) y <10 is TRUE (1) Note that since the operator < enjoys a higher priority compared to ==, y < 10 is tested first and then x ==25 is tested. Finally we get, Relational operators precedence if (FALSE && TRUE) Because one of the conditions is FALSE, the complex condition is FALSE. In the case of &&, it is guaranteed that the second operand will not be evaluated if the first is zero 47and in the case of, the second operand will not be evaluated if the first is non zero. Precedence and Associativity Table The following table lists all the operators, in order of precedence, with their associativity Operators Operations Associativity priority () Function call Left to Right 1 [] Square brackets -> Structure operator. Dot operator + Unary plus Right to Left 2 - Unary minus ++ Increment -- Decrement! Not 48 12

Precedence and Associativity Table cont. Precedence and Associativity Table cont. Operators Operations Associativity priority Operators Operations Associativity priority ~ Complement Right to Left 2 << Left shift Left to Right 5 * Pointer operation >> Right shift < is less than Left to Right 6 & Address operator <= is less than or equal to Sizeof Size of operator > is greater than type Type cast >= is greater than or equal to * Multiplication Left to Right 3 == equal to / Division!= not equal to % Modulo & Bitwise AND Left to Right 7 + Addition Left to Right 4 Bitwise OR - Subtraction 49 ^ Bitwise XOR 50 Precedence and Associativity Table cont. Operators Operations Associativity priority && Logical And Left to Right 8 Logical OR?= Conditional Right to Left 9 =,*=,- =,&=,+=,^=,!=, <<=,>>= Assignment Right to Left 10, comma Left to Right 11 Rules for evaluation of expression Evaluate the sub expression from left to right if parenthesized. Evaluate the arithmetic expression from left to right using the rules of precedence. The highest precedence is given to the expressions with in parenthesis. Apply the associative rule if more operators of the same precedence occurs. Evaluate the inner most sub expression if the parenthesis are nested. 51 52 13

Exp = a - 2 * a * b + b / 4 Sample Expression Let us have a=10,b=20 exp = 10-2 * 10 * 20 + 20 / 4 Phase I exp = 2*10*20, 20/4 will be evaluated. phase II exp = 10-400+5 will be evaluated. Expression Evaluation Let us see some examples for evaluating expression. Let a = 5, b = 8, c = 2. x = b / c + a * c 4 10 14 Result exp = -395. 53 54 Expression Evaluation Let us see some examples for evaluating expression. Let a = 5, b = 8, c = 2. y = a + (b * 3) - c 24 29 27 TYPE CONVERSION OR TYPE CASTING 55 56 14

What is Type Conversion or Type Casting Type Casting means One data type converted into another data type. This is called Type conversion or Type casting. Example: 1. Integer into floating point number 2. Character into integer 3. Floating point number into Integer Number Type conversion is classified into two types. 1. Implicit Type Conversion (Automatic Type Conversion) 2. Explicit Type Conversion (Manual Type Conversion) Type Conversion Type Conversion Hierarchy Implicit Type Conversion unsigned int long int unsigned long int float double long double Implicit Conversion Automatic Conversion Explicit Conversion Casting Operation 57 short int char Explicit Type Conversion 58 Implicit Type Conversion 1. The Implicit Type Conversion is known as Automatic Type Conversion. 2. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. 3. Implicit type Conversion also known as Converted Lower order data type into Higher order data type. 4. Implicit Type Conversion also known as Widening. Explicit Type Conversion 1. The Explicit Type Conversion is, there are instances when we want to force a type conversion in a way that is different from the automatic conversion. 2. The Explicit Type Conversion is Converted Higher order data type into Lower order data type. 3. The Explicit type Conversion is also known as borrowing. 4. The Explicit type conversion forces by a casting operator. Example: int a, b; float c; c = a + b; Disadvantage of Explicit Type Conversion 1. float to int causes truncation of the fractional part. 2. double to float causes rounding of digits. 3. Long int to int causes dropping of the excess higher order bits. Print c; The general form of the casting is float a,b; int c; c = a + b; Print c; // This is Wrong (type_name) expression; Where type_name is one of the standard C data type. The expression may be a constant, variables or an expression. For Example: float a, b; int c; 59 c = (int) a + (int) b; Print c; 60 15

Use of Casts Example Action x = (int) 7.5 7.5 is converted to integer by truncation. a = (int) 21.3 / (int) 4.5 Evaluated as 21 / 4 and the result would be 5. Input And Output Functions b = (double) sum / n y = (int) (a + b) Division is done in floating point mode. The result of a + b is converted to integer. z = (int) a + b a is converted to integer and then added to b. p = cos ((double) x) Converts x to double before using it. 61 62 Ip / Op Statements Ip / Op Statements cont. We have two methods for providing data to the program. a) Assigning the data to the variables in a program. b) By using the input/output statements. Ip / Op Functions c language supports two types of Ip / Op statements This operations are carried out through function calls. Those function are collectively known as standard I / O library 63 Unformatted Ip / Op statements Input Output getc() putc() getch() putch() Gets() puts() Formatted Ip / Op statements Input Output Scanf() printf() fscanf() fprintf() 64 16

Unformatted Ip / Op statements These statements are used to input / output a single / group of characters from / to the input / output device. Single character Input/output function Unformatted Ip / Op statements cont. Group of character Input / output function. Gets() and puts are used to read / display the string from / to the standard input / output device. getch() function Syntax char variable = getch(); Description char is the data type of the variable; getch() is the function putch() function Syntax Description putch (character variable); char variable is the valid c variable of the type of char data type. gets() function Syntax Description gets (char type of array variable); valid c variable declared as one dimensional array. puts() function Syntax Description puts (char type of array variable) valid c variable declared as one dimensional array. Example char x = getch(); putch (x); Example char s[10]; Example char x ; putch (x); Example char s[10]; gets (s); 65 gets (s); puts (s); 66 Sample Program #include<stdio.h> Void main() char name[10]; char address[20]; Puts( Enter the name : ); gets(name); puts( Enter the address : ); gets(address); puts( Name = ) puts(name); puts( Address = ); puts(address); 67 Formatted Ip / Op statements It refers to Input / Output that has been arranged in a particular format. Using this statements, the user must specify the type of data, that is going to be accessed. scanf() (This function is used to enter any combination of input). Syntax Description Example int n; scanf ( %d, &n); scanf ( control strings,var1,var2..var n); control strings is the type of data that user going to access via the input statements. var1,var2 are the variables in which the data s are stored. 68 17

Formatted Ip / Op statements Control strings i) It is the type of datathat user is going to access via the input statement ii) These can be formatted. iii) Always preceded with a % symbol. Format code Variable type Display %c Char Single character %d Int Decimal integer -32768 to 32768 %s Array of char Print a Strings %f Float or double Float point value without exponent %ld Long int Long integer -65536 to 65535 %u Int Unsigned decimal integer %o Int Octal integer number without leading zero %x Int Hexadecimal integer number without leading 0x %e Float or double Float point values in exponent form Rules for scanf() The control strings must be preceded with % sign and must be within quotations. If there is a number of input data items, items should be separated by commas and must be preceded with & sign except for char data types. The control strings and the variables going to input should match with each other. It must have termination. The scanf() reads the data values until the blank space in numeric input. Apart from % it can have * sign. This is used to ignore the values inputted. eg: scanf( %d%d%*d%*d%d,&i,&j,&k); if the input is 10 20 3040 50 The output will be i = 10, j = 20, k = 50; %h int Short integer 69 70 Printf() Rules for printf() printf() (This function is used to display the result or the output data on to screen) Syntax Description Example printf ( control strings,var1,var2..var n); Control strings can be anyone of the following a) Format code character code b) Execution character set c) Character/strings to be displayed Var1,var2 are the variables in which the data s are stored. printf ( this is computer fundamental class ); printf ( /n computer fundamental class ); 71 variables should be separated by commas and need not be preceded with & sign. The control strings and the variables must match with each other. The control string must be in quotations and there we can also use any other text to print with data. 72 18

Formatted IO / OP Writing integers numbers Formatted IO / OP Writing Real Numbers Syntax Description Example Printf (%w.pd,var1) W is used to specify the minimum field width for the output. P is the precession value. D is the control string specification Printf ( %5.4d,23); The output will be $0023. Printf ( %05d,23); The output will be 00023. 73 Syntax Description Example Printf (%w.p.f,var1) W is used to specify the minimum field width for the output. P is the number of digits to be displayed after the decimal point. f is the control string for float. Printf ( %5.2.f,2345.567890); The output will be $2345.56. Printf ( %10.2e,48.3333); The output will be 4.8e+01 74 Sample Program include<stdio.h> include<conio.h> void main() int r,t; char u,y; float a,b,c,d; clrscr(); scanf("%d%d",&r,&t); printf("enter the char value"); scanf("%c",&y); printf("\n%9c%9c",r,t); printf("\n\t%d\t\%d",r,t); printf("\n the value of u is %c",y); getch(); 75 Control Statements (Decision Making) 76 19

Control Statements A program consists of a number of statements which are usually executed in sequence. Programs can be much more powerful if we can control the order in which statements are run. Statements fall into three general types; Control Statements Control statements in C are used to write powerful programs by; Repeating important sections of the program. Selecting between optional sections of a program. 1) Assignment, where values, usually the results of calculations, are stored in variables. 2) Input / Output, data is read in or printed out. 3) Control, the program makes a decision about what to do next. 77 78 The if else statement The switch statements Control Statements Selection Statements Control statements Iteration statements The while loop & Do while loop The for loop The break statement Continue statement Control Statements cont. Structure Meaning Example C language provides four general structure by which statements can be Sequential executed It means the instructions are carried out in sequence a+=5; a=a+b; Selection Iteration Encapsulation Sequence of the instruction are determined by the result of the condition Here the statements are repeatedly executed Here the an iteration statement can have selection inside it or vice versa if (x>y) a = a+1; else a= a-1; while (a<=10) printf ( %d, a); while (a<=10) if(a>5) printf (%d, a); Goto statement 79 80 20

Types of Selection Statement SELECTION STATEMENT 1. Simple if Selection statement 2. if else Selection statement 3. Nested if else Selection statement 4. else if ladder Selection statement 81 82 Simple if Selection statement It is used to control the flow of execution of the statements and also to test logically whether the condition is true or false. Syntax: if ( condition ) statement ; if the condition is true then the statement following the if is executed if it is false then the statement is skipped. Test Condition True Executable X - Statement Selection Statement Properties of an if statement a) if the condition is true then the simple or compound statements are executed. b) If the condition is false it will skip the statement. c) The condition is given in parenthesis and must be evaluated as true or false. d) If a compound structure is provided, it must be enclosed in opening and closing braces 83 84 21

//Biggest of Two Numbers #include <stdio.h> void main() int a, b; clrscr(); printf( Enter the A and B Value:\n ); scanf( %d, &a); if (a > b) printf( A is Big ); getch(); 85 Basic Relational Operators Basic Relational Operators can be used in C to make if statement conditions more useful The 6 Basic Relational Operators are >, <, >=, <=, ==,!= (greater than, less than, greater than or equal to, less than or equal to, equal to, not equal to) Basic Logic Operators Basic Logic Operators can be used to combine more than one condition in an if statement or invert the result of a condition The 3 Basic Logic Operators are &&,,! (and, or, not) 86 The if else statement It is used to execute some statements when the condition is true and execute some other statements when the condition is false depending on the logical test. Syntax: if ( condition ) statement 1 ; else statement 2 ; (if the condition is true this statement will be executed) (if the condition is falsethis statement will be executed) if else statements if (result >= 45) printf ( Passed\n ) ; printf ( Congratulations\n ) else printf ( Failed\n ) ; printf ( Good luck in the resits\n ) ; False Test Condition True Executable Y - Statement Executable X - Statement 87 88 22

// Biggest of Two Numbers #include <stdio.h> void main() int a, b; clrscr(); printf( Enter the A and B Value:\n ); scanf( %d, &a); // Given Number is ODD or EVEN Number #include <stdio.h> void main() int n; clrscr(); printf( Enter the Number:\n ); scanf( %d, &n); if (a > b) printf( A is Big ); else printf( B is Big ); getch(); if (n % 2 == 0) printf( Given Number is Even Number ); else printf( Given Number is Odd Number ); getch(); 89 90 Nested if.. else statement when a series of if else statements are occurred in a program, we can write an entire if else statement in another if else statement called nesting FALSE Test Condition_1 TRUE Syntax: if ( condition 1) if ( condition 2) statement 1 ; else statement 2 ; else if (condition 3) statement 3; else statement 4; FALSE Executable X2 - Statement FALSE TRUE Test Condition_3 Executable X4 - Statement Executable X3 - Statement Test Condition_2 TRUE Executable X1 - Statement 91 92 23

// Biggest of Three Numbers #include<stdio.h> void main() int a, b, c; clrscr(); else if Ladder or Multiple if else Statements When a series of decisions are involved we have to use more than one if else statement called as multiple if s. Multiple if else statements are much faster than a series of if else statements, since theif structure is exited whenany one of the conditionis satisfied. printf( Enter the Three Numbers:\n ); scanf( %d%d%d,&a,&b,&c); if (a > b) if (a > c) else printf( A is Big ); printf( C is Big ); else if (b > c) printf( B is Big ); else printf( C is Big ); getch(); executed statement_x; 93 94 Syntax: if (condition_1) executed statement_1; else if (condition_2) executed statement_2; else if (condition_3) executed statement_3; ---------------------- ---------------------- else if (condition_n) executed statement_n; else else if Ladder FALSE Test Condition_1 TRUE Exec. Stat_1 FALSE FALSE FALSE Test Condition_3 TRUE Test Condition_n TRUE Test Condition_2 Exec. Stat_3 TRUE Exec. Stat_2 if (result >= 75) printf ( Passed: Grade A\n ) ; else if (result >= 60) printf ( Passed: Grade B\n ) ; else if (result >= 45) printf ( Passed: Grade C\n ) ; else printf ( Failed\n ) ; Exec. Stat_X Exec. Stat_n 95 96 24

/*This program reads in a simple expression with a very restricted format and prints out its value. */ main() int n1,n2; int val; char op; printf("enter a simple expression "); scanf("%d%c%d",&n1,&op,&n2); if(op == '+') val = n1 + n2; else if(op == '-') val = n1 - n2; else if(op == '/') val = n1 / n2; else if(op == '*') val = n1 * n2; else printf(?? operator %c\n",op); exit(1); printf("%d%c%d = %d\n",n1,op,n2); 97 Sample Program Write a program to calculate the sales commission for the data given below: Sales value (Rs) Less than 1000 Above 1000 but below 2000 Above 2000 but below 5000 Above 5000 Commission(%) No commission 5% of sales 8% of sales 10% of sales 98 #include<stdio.h> #include<conio.h> Void main() float sales, com; printf( Enter the sales value : ); scanf( %f, &sales); if(sales<=1000) com = 0; else if(sales>1000 && sales <=2000) com = sales*5/100; else if(sales>2000 && sales <=5000) com = sales*5/100; else com = sales * 10/100; printf( The commission for the sales value %f is %f, sales, com); 99 THE SWITCH STATEMENT The control statements which allow us to make a decision from the number of choices is calledswitch (or) Switch-casestatement. It is a multi way decision statement, it test the given variable (or) expression againsta listof casevalue. switch (expression) case constant 1: simple statement (or) compound statement; case constant 2: simple statement (or) compound statement; case constant 3: simple statement (or) compound statement; switch (expression) case constant 1: simple statement (or) compound statement; case constant 2: simple statement (or) compound statement; default : simple statement (or) compound statement; 100 25

Example Without Break Statement #include<stdio.h> void main () int num1,num2,choice; printf( Enter the Two Numbers:\n ); scanf( %d%d,&num1,&num2); printf( 1 -> Addition\n ); printf( 2->Subtraction\n ); printf( 3->Multiplication\n ); printf( 4->Division\n ); printf( Enter your Choice:\n ); scanf( %d,&choice); switch(choice) case 1: Printf( Sum is %d\n, num1+num2); case 2: Printf( Diif. is %d\n, num1-num2); case 3: Printf( Product is %d\n, num1*num2); case 4: Printf( Division is %d\n, num1/num2); default: printf ( Invalid Choice..\n ); Example With Break Statement #include<stdio.h> void main () int num1,num2,choice; printf( Enter the Two Numbers:\n ); scanf( %d%d,&num1,&num2); printf( 1 -> Addition\n ); printf( 2->Subtraction\n ); printf( 3->Multiplication\n ); printf( 4->Division\n ); printf( Enter your Choice:\n ); scanf( %d,&choice); switch(choice) case 1: printf( Sum is %d\n, num1+num2); break; case 2: printf( Diif. is %d\n, num1-num2); break; case 3: printf( Product is %d\n, num1*num2); break; case 4: printf( Division is %d\n, num1/num2); break; default: printf ( Invalid Choice..\n ); Fall through Statement in C getch(); getch(); 101 102 Rules for Switch The expressioninthe switchstatementmustbean integeror characterconstant. No real numbers are usedin an expression. The defaultis optional andcan be placedanywhere, butusually placedatend. The casekeywordmustbe terminatedwithcolon (:); No two caseconstantareidentical. The values of switch expression is compared with case constant in the order specified i.e from top to bottom. The compoundstatements areno needto enclosewithinpairof braces. Integer Expressionusedindifferentcasestatements canbe specifiedinany order. A switch may occur within another switch, but it is rarely done. Such statements are called as nestedswitchstatements. The switchstatementis very useful whilewritingmenudrivenprograms. Limitations of using a switch statement Only One variable can be tested with the available case statements with the values stored in them (i.e., you cannot use relational operators and combine two or more conditions as in the case of if or if else statements). Floating point, double, and long type variables cannot be used as cases in the switch statement. Multiple statements can be executed in each case without the use of pair of braces as in the caseof if or if elsestatement. 103 104 26

Iteration Statements 1. Iteration statements is also known as Looping statement. 2. A segment of the program that is executed repeatedly is called as a loop. 3. Some portion of the program has to be specified several number of times or until a particular condition is satisfied. 4. Such repetitive operation is done through a loop structure. 5. The Three methods by which you can repeat a part of a program are, 1. while Loops 2. do.while loops 3. for Loop Loops generally consist of two parts : Any looping statement, would include the following steps: a) Initialization of a condition variable b) Test the control statement. c) Executing the body of the loop depending on the condition. d) Updating the condition variable. Control expressions: One or more control expressions which control the execution of the loop, Body : which is the statementor set of statements which is executed over and over 105 106 While Loop Start A while loop has one control expression, and executes as long as that expression is true. The general syntax of a while loop is Initialize initialize loop counter; while (condition) statement (s); increment or decrement loop counter Test Condition True False Stop A while loop is an entry controlled loop statement. Body of Loop Increment or Decrement 107 108 27

Example: // Print the I Values #include <stdio.h> void main() int i; clrscr(); i = 0; while(i<=10) printf( The I Value is :%d\n,i); ++I; getch(); // Summation of the series 1 + 2 + 3 + 4 +. #include <stdio.h> void main() int i, sum; clrscr(); i = 1; sum = 0; while(i<=10) sum = sum + i printf( The Sum Value is:%d\n,i); ++I; getch(); 109 Example: //Summation of the series 1 2 + 2 2 + 3 2 +.. #include <stdio.h> #include<math.h> void main() int i, sum; clrscr(); i = 1; sum = 0; while(i<=10) sum = sum + i*i; //or I ^2 or pow(i, 2) printf( The Sum Value is:%d\n,i); ++I; //Summation of the series 1 1 + 2 2 + 3 3 +.. #include <stdio.h> #include<math.h> void main() int i, sum; clrscr(); i = 1; sum = 0; while(i<=10) sum = sum + pow(i,i) printf( The Sum Value is:%d\n,i); ++I; getch(); 110 getch(); #include<stdio.h> void main() int number=0, rem=0, sum=0; Wap to print the summation of digits of any given number. clrscr(); printf( Enter the value for number ); scanf( %d,&n); while(number > 0) rem = number % 10; sum = sum + rem; number = number / 10; printf( the summation value of the given number %d is = %d,number,sum); 111 THE do-while LOOP The body of the loop may not be executed if the condition is not satisfied in while loop. Since the test is done at the end of the loop, the statements in the braces will always be executed at least once. The statements in the braces are executed repeatedly as long as the expression in the parentheses is true. initialize loop counter; do statement (s); increment or decrement loop counter while (condition); Make a note that do while ends in a ; (semicolon) Note that Do While Looping statement is Exit Controlled Looping statement112 28

Start Difference Between While Loop and Do While Loop Initialize Sl.No. while loop do-while loop Body of Loop 1. The while loop tests the condition before each iteration. The do while loop tests the condition after the first iteration. Increment or Decrement 2. If the condition fails initially the loop is Skipped entirely even in the first iteration. Even if the condition fails initially the loop is executed once. True Test Condition Stop False 113 114 Example: // Print the I Values #include <stdio.h> void main() int i; clrscr(); i = 0; do printf( The I Value is :%d\n,i); ++I; while(i<=10); getch(); // Print the I Values #include <stdio.h> void main() int i; clrscr(); i = 11; do printf( The I Value is :%d\n,i); ++I; Wap to print the Fibonacci series for any given number Using Do.While Loop #include <stdio.h> void main() int i, f1,f2,f3; clrscr(); f1 = 0; f2 = 1; printf( The Fibonacci Series is:\n ) printf( %d\n,f1); printf( %d\n,f2); do f3 = f1 + f2; printf(%d\n,f3); f1 = f2; f2 = f3; ++i; while(i<=10); while(i <= 10); getch(); 115 getch(); 116 29

for Loop The for loop is another repetitive control structure, and is used to execute set of instruction repeatedly until the condition becomes false. To set up an initial condition and then modify some value to perform each succeeding loop as long as some condition is true. Start The syntax of a for loop is Initialize; test_condition; Increment / Decrement for( expr1; expr2 ;expr3) Body of the loop; Body of Loop The three expressions : expr1 - sets up the initial condition, expr2 - tests whether another trip through the loop should be taken, expr3 - increments or updates things after each trip. 117 Stop 118 Exampl e Given example will print the values from 1 to 10. #include<stdio.h> void main() for (int i = 1; i <= 10; i++) printf("i is %d\n", i); There is no need of braces for single line statement and for multiple line it is essential else it will consider only next line of for statement. Exampl e Given example of Multiplication Table #include<stdio.h> #include<conio.h> void main() int mul,limit,c,i; clrscr(); printf("enter the Multiplication Number:\n"); scanf("%d",&mul); printf("enter the Limits:\n"); scanf("%d",&limit); for(i=1;i<=limit;i++) c = i * mul; printf("%d * %d: %d\n",i,mul,c); 119 getch(); 120 30

Additional Features of for Loop Case 1: The statement p = 1; for (n = 0; n < 17; ++ n) can be rewritten as for (p = 1, n = 0; n < 17;++n) Case 2: The second feature is that the test condition may have any compound relation and the testing need not be limited only to the loop control variable. sum = 0; for (i = 1; i < 20 && sum < 100; ++ i) sum = sum + i; printf( %d %d\n, i, sum); 121 Additional Features of for Loop Conti Case 3: It also permissible to use expressions in the assignment statements of initialization and increments sections. For Example: for (x = (m + n) / 2; x > 0; x = x / 2) Case 4: Another unique aspect of for loop is that one or more sections can be omitted, if necessary. For Example: m = 5; for ( ; m! = 100 ;) printf( %d\n,m); m = m + 5; Both the initialization and increment sections are omitted in the for statement. The initialization has been done before the for statement and the control variable is incremented inside the loop. In such cases, the sections are left blank. However, the semicolons separating the sections must remain. If the test condition is not present, the for statement sets up an infinite loop. Such loops can be broken using break or goto statements in the loop. 122 Additional Features of for Loop Conti Case 5: We can set up time delay loops using the null statement as follows: for ( j = 1000; j > 0; j = j 1) 1. This is loop is executed 1000 times without producing any output; it simply causes a time delay. 2. Notice that the body of the loop contains only a semicolon, known as a null statement. Case 6: for ( j = 1000; j > 0; j = j 1) This implies that the C compiler will not give an error message if we place a semicolon by mistake at the end of a for statement. The semicolon will be considered as a null statement and the program may produce some nonsense. Nesting of for Loop The One for statement within another for statement is called Nesting for Loop. Syntax: for (initialize; test_condi; incre. / decre.) --------------- --------------- for (initialize; test_condi; incre. / decre.) ----------- ----------- --------------- --------------- ----------------- ----------------- Inner for Loop Outer for Loop 123 124 31

Example // Print the I and J Value #include<stdio.h> #include<conio.h> void main() int I, j; clrscr(); for (i = 1; I < = 10 ; I ++) printf ( The I Value is %d \n", i); getch(); for (j = 1; j < = 10; j ++) printf ( The J Value is %d \t", j); Example // Multiplication Table #include<stdio.h> #include<conio.h> void main() int sum = 1,a,b; clrscr(); for (a=1;a<=5;a++) printf ("the multiplication table for %d\n",a); getch(); for (b=1;b<=12;b++) sum=a*b; printf("%d*%d=",a,b); printf("%d\n",sum); sum = 0; 125 126 Exercise 1) Write a program that will read in N numbers and print out their average. 2) Wap to print the following series for N given number 1+(1+2)+(1+2+3)+(1+2+3+4) 3) Wap to print the following series for N given number + ++ +++ ++++ +++++ ++++++.. 4) Wap to print the following series for N given number 1 111 11111 1111111 JUMPS IN LOOPS 127 128 32

1. Loops perform a set of operations repeatedly until the control variable fails to satisfy the test condition. 2. The number of times a loop is repeated is decided in advance and the test condition is written to achieve this. 3. Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to leave the loop as soon as a certain condition occurs. 4. Jumps out of a Loop is Classified into three types 1. break; 2. continue; 3. goto; The break Statement 1. A break statement is used to terminate of to exit a for, switch, while or do while statements and the execution continues following the break statement. 2. The general form of the break statement is break; 3. The break statement does not have any embedded expression or arguments. 4. The break statement is usually used at the end of each case and before the start of the next case statement. 5. The break statement causes the control to transfer out of the entire switch statement. 129 130 #include <stdio.h> void main() int i; clrscr(); i = 1; #include<stdio.h> void main () int num1,num2,choice; printf ( Enter the Two Numbers:\n ); scanf( %d%d,&num1,&num2); printf( 1 -> Addition\n ); printf( 2->Subtraction\n ); printf( 3->Multiplication\n ); printf( 4->Division\n ); printf ( Enter your Choice:\n ); scanf ( %d, &choice); while (i < = 10) printf ( The I Value is: %d \n, i); if (i = = 6) printf ( The I value is Reached 6, So break of the programs\n ); break; ++ i 131 switch (choice) case 1: printf ( Sum is %d \n, num1+num2); break; case 2: printf ( Diif. is %d \n, num1-num2); break; case 3: printf ( Product is %d \n, num1*num2); break; case 4: printf ( Division is %d \n, num1/num2); break; default: printf ( Invalid Choice..\n ); getch(); 132 33

The continue Statement The continue statement is used to transfer the control to the beginning of the loop, there by terminating the current iteration of the loop and starting again from the next iteration of the same loop. The continue statement can be used within a while or a do while or a for loop. The general form or the syntax of the continue statement is continue; The continue statement does not have any expressions or arguments. Unlike break, the loop does not terminate when a continue statement is encountered, but it terminates the current iteration of the loop by skipping the remaining part of the loop and resumes the control tot the start of the loop for the next iteration. 133 #include <stdio.h> void main() int i; clrscr(); i = 1; while (i < = 10) printf ( The I Value is: %d \n, i); if (i = = 6) printf ( The I value is Reached 6, But Continue this Programs\n ); continue; ++ i 134 Differences Between Break and Continue Statement Sl.No. break continue 1. Used to terminate the loops or to exit loop from a switch. 2. The break statement when executed causes immediate termination of loop containing it. Used to transfer the control to the start of loop. Continue statement when executed causes Immediate termination of the current iteration of the loop. The goto Statement The goto statement is used to transfer the control in a loop or a function from one point to any other portion in that program. If misused the goto statement can make a program impossible to understand. The general form or the syntax of goto statement is The goto statement is classified into two types a. Unconditional goto b. Conditional goto goto label; Statement (s);. label: statement (s); 135 136 34

Unconditional Goto The Unconditional goto means the control transfer from one block to another block without checking the test condition. Example: #include <stdio.h> void main() clrscr(); Start: getch(); printf( Welcome\n ); goto Start; 137 Conditional Goto The Conditional goto means the control transfer from one block to another block with checking the test condition. #include <stdio.h> void main() int a, b; clrscr(); printf ( Enter the Two Value:\n ); scanf ( %d, &a, &b); if (a > b) goto output_1; else goto output_2; output_1: printf ( A is Biggest Number ); goto Stop; output_2: printf ( B is Biggest Number ); goto Stop; Stop: getch(); 138 UNIT IV ARRAYS AND FUNCTIONS Arrays 139 140 35

Definition of Array An array is a fixed size sequenced collection of elements of the same data type. It is simply a grouping of like type data. In its simplest form, an array can be used to represent a list of numbers, or list of names. (OR) Array is a Collection of Homogenous Data Items Example 1. List of temperatures recorded every hour in a day, or a month, or a year. 2. List of employees in an organization. 3. List of products and their cost sold by a store. 4. Test Scores of a class of students. Types of Array 1. One Dimensional Array 2. Two Dimensional Array 3. Multi Dimensional Array 141 142 One Dimensional Array Y X Arrays So far, we've been declaring simple variables int i; It is also possible to declare an array of Several elements. an array is a variable that can hold more than one value, The declaration int a[10]; declares an array, named a, consisting of ten elements, each of type int. We can represent the array a above with a picture like this: Z One Dimensional Array is defined any one of axis (X or Y or Z) in the graph 143 Arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9. 144 36

Arrays An array uses a single identifier, together with an integer index, to create one variable that can hold many values An array is created the same as a normal variable, but with the addition of square brackets indicating the size of the array Each value in an array is accessed using the identifier and a valid index in square brackets Each value in the array is called an element, and the identifier by itself resolves to the address of where the array is in memory Syntax Description Example One Dimensional Arrays data_type array_name[size]; Data_type valid data type in C language Array_name name given to the array Size1 are the size of the dimensions Int a[3]; Float b[4]; 145 146 Initializing Arrays An array is initialized using a code block containing comma-delimited values which match in position the elements in the array If there are values in the initialization block, but not enough to fill the array, all the elements in the array without values are initialized to 0 in the case of float or int, and NULL in the case of char If there are values in the initialization block, an explicit size for the array does not need to be specified, only an empty Array Element Operator. C will count the values and size the array for you Initializing Arrays int x [ 5 ] = 1,2,3,4,5 ; size 10 bytes creates array with elements 0-4 values 1-5 int x [ 5 ] = 4,3 ; size 10 bytes creates array with elements 0-4 values 4,3,0,0,0 int x [ ] = 1,2,3 ; size 6 bytes creates array with elements 0-2 values 1,2,3 char c [ 4 ] = M, o, o ; size 4 bytes creates array with elements 0-3 values M o o NULL 147 148 37

Arrays Cont The first element of the array is x[0], the second element is x[1].. e.g x[0] = 10; x[1] = 20; x[2] = 30 x[3] = 40 x[4] = 50 Total = 150; This loop sets all ten elements of the array a to 0. int a[i]; int i; for(i = 0; i < 10; i = i + 1) a[i] = 0; To copy the contents of one array to another, you must again do so one by one: int b[10]; for(i = 0; i < 10; i = i + 1) b[i] = a[i]; Printing Array Values for(i = 0; i < na; i = i + 1) Array Basics An array has a fixed number of elements based on its creation The elements are ALWAYS numbered from 0 to 1 less than the array s size Referencing an element outside of the created bounds is possible but not recommended printf("%d\n", a[i]); 149 150 Visual Representation of an Array Address int x[4]; Offset x[2]=23; 342901 342905 342909?? 23 0 1 2 X Identifier The Array Element Operator [ ] The Array Element Operator is used to reference a specific array element The expression inside the Array Element must resolve to type int. This value is known as an index The value of the index can be any number, but care should be taken that the index falls within the bounds of the array. The bounds of an array are defined as 0 to 1 less than the size of the array 342913? 3 Value 151 152 38

Array Example #include <stdio.h> int main(void) int x[5]; x[0]=23; valid x[2.3]=5; invalid: index is not an int x[6]=45; valid but not recommended return 0; 153 A Simple Array Example #include <stdio.h> int main(void) int i, x[ 5 ], total = 0 ; for ( i = 0 ; i < 5 ; i++ ) printf( Enter mark %d, i ); scanf ( %d, &x[ i ] ); for ( i = 0 ; i < 5 ; i++ ) total = total + x[ i ]; printf ( The average is %d, total / 5 ); return 0; 154 ARRAYS DON'T declare arrays with subscripts larger than you will need; it wastes memory. DON'T forget that in C, arrays are referenced starting with subscript 0, not 1. Sample program #include<stdio.h> main() int a[5],i; printf( enter the array elements ); for(i = 0;i<5;i++) scanf( %d,&a[i]); printf( Array in the reverse order ); for(i = 5;i>0;i--) printf( %d,a[i]; 155 156 39

#inlcude<stdio.h> #define Max 5; main(); int a[max], i, min; int pos = 0; printf( Enter the array elements ); for(i=0;i<5;i++) scanf( %d,&a[i]); min = a[0]; for(i=1;i<max;i++) if(a[i] < min) min = a[i]; pos = i; printf( Minimum Value = %d, min); printf( Position of the Minimum Value = %d, pos); 157 Identify the errors if any, 1) #define Max 1.5; main() int a[max]; 2) main() int i,a[5]; for(i=0;i<5;i++); a[i] = 0; Exercise 158 main() int size; scanf( %d,&size); int arr[size]; for(int i=1;i<size;i++) scanf( %d,&arr[i]); printf( %d,arr[i]); 159 State whether the following are true or false 1) The array int num[26] has twenty-six elements. 2) The expression num[1] designates the first element in the array. 3) The expression num[27] designates the twenty-eighth element in the array. What is the difference between the 5 s in these two expressions int num[5]; num[5] = 200; 160 40

Two-Dimensional Arrays Two-dimensional Array: a collection of a fixed number of components arranged in two dimensions All components are of the same type The syntax for declaring a two-dimensional array is: datatype arrayname[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding Two-Dimensional Arrays (continued) The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array Two-dimensional arrays are sometimes called matrices or tables positive integer values 161 162 Two Dimensional Array Y X Z Two Dimensional Array is defined any Two of axis of XY or YZ or ZX in the graph 163 164 41

Syntax Description Example Two Dimensional Arrays data_type array_name[size_1][size_2]; Data_type valid data type in C language Array_name name given to the array Size_1 is the row size of the array Size_2 is the column size of the array int a[3][3]; float b[4][4]; Int a[3][2]; Two Dimensional Array Initializing int table [2][3] = 0,0,0,1,1,1; int table [2][3] = 0,0,0,1,1,1; int table [2][3] = 0,0,0, 1,1,1 ; int table [ ][3] = 0,0,0 1,1,1 ; 165 166 Two Dimensional Array Initializing If the values are missing in an initializer, they are automatically set to zero. For instance, the statement int table [2][3] = 1,1, 2 ; will initialize the first two elements of the first row to one, the first element of the second row to two, and all other elements to zero. When all the elements are to be initialized to zero, the following short cut method may be used. int m[3][5] = 0,0,0 ; The first element of each row is explicitly initialized to zero while other elements are automatically initialized to zero, The following statement will also achieve the same result: int m[3][5] = 0,0; 167 Accessing Array Components The syntax to access a component of a two-dimensional array is: arrayname[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values indexexp1 specifies the row position and indexexp2 specifies the column position 168 42

0 1 2 0 1 2 Multi Dimensional Arrays Three or More Dimensional Array is called the Multi Dimensional Arrays. Y 3 4 25.75 X 169 Z Three Dimensional array defined in any three of axis of XYZ OR YZX OR ZXY 170 in the graph Multi Dimensional Arrays This arrays have more than one dimensions. Syntax Description Example data_type array_name[size1][size2].[sizen]; Data_type valid data type in C language Array_name name given to the array Size1,size2 are the sizes of the dimensions Int a[3][3][3]; Float b[4][4][4]; CHARACTER ARRAYS AND STRINGS 171 172 43

Character and Strings An char array is a group of characters that store related data A String is a special char array that does not store related data, but a single piece of data made up of a number of characters OR A string is a sequence of character that is treated as a single data item. Any group of characters defined between double quotation marks is a string constant. Example: Grades can be stored in a char array with the values A,B,C,D,F; when we want to print a specific grade we use only 1 element of the array Example: But for grades like Pass and Fail we must print ALL the elements 173 String Conti Most Computers languages have a string data type; C does NOT There are 3 ways to store strings in memory Fixed Length Stored Length Terminated C adopts the Terminated String approach A string is C is an array of chars terminated by the String Terminator or NULL character \0 174 Common String Operation 1. Reading and Writing Strings 2. Combining strings together 3. Copying one string to another 4. Comparing strings for equality 5. Extracting a portion of a string Declaring and Initializing of String The General form of String is char string_name [size]; Example: char city [10]; char name[30]; When the complier assigns a character string to a character array, it automatically supplies a multicharacter ( \0 ) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one. C Permits a character array to be initialized in either of the following two forms: char city [9] = NEW YORK ; char city [9] = N. E, W,, Y, O, R, K, \0 ); C also permits us to initialize a character array without specifying the number of elements. In such cases, the size of the array will be determined automatically, base on the number of elements initialiazed. For Example, the statement char string [ ] = G, O, O, D, \0 ; 175 176 44

DeclaringConti. We can also declare the size much larger than the string size in the initializer. That is, the statement. Creating a String in C char str[9] = GOOD ; G O O D \0 \0 \0 \0 \0 The following declaration is illegal. (I) char str[5]; str = GOOD ; This will result in a compile time error. Also note that we cannot separate the initialization from declaration. (II) char s1[4] = abc ; char s2[4]; s2 = s2; /* Error */ 1820 1821 1822 h i! array 2820 2821 2822 2823 h i! /0 string is not allowed. An array name cannot be used as the left operand of an assignment operator. 177 178 READING STRINGS FROM TERMINAL The familiar input function scanf can be used with %s format specification to read in a string of characters. Example: char address [10]; scanf( %s,address); The problem with the scanf function is that it terminates its input on the first white space it finds. Therefore, if the following line of text is typed in at the terminal, NEW YORK then only the string NEW will be read into the array address, since the blank space after the word NEW will terminate the string reading. The scanf calls in the case of character arrays, the ampersand (&) is not required before the variable name. The address array is created in the memory as shown below: N E W \O?????? Note that the unused locations are filled with garbage. If we want to read the entire line NEW YORK, then we may use two character arrays of approximate sizes. That is, With the line of text char adr1[5], adr2[5]; scanf( %s %s,adr1,adr2); NEW YORK 179 READING STRINGS FROM TERMINAL We can also specify the field width using the form %ws in the scanf statement for reading a specified number of characters from the input string. Example: Here two things may happen. scanf( %ws,name); 1. The width w is equal to or grater than the number of characters typed in. The entire string will be stored in the string variable. 2. The width w is less than the number of characters in the string. The excess characters will be truncated and left unread. Consider the following statements: char name [10]; scanf( %5s,name); The input string RAM and KRISHNA will be stored as: R A M \0?????? K R I S H \0???? 180 45

Reading a Line of Text We have seen just now that scanf with %s or %ws can read only strings without white spaces. That is, they cannot be used for reading a text containing more than one word. However, C Supports a format specification known as the edit set conversion code % [..] that can be used to read a line containing a variety of characters, including white spaces. Recall that we have used this conversion code in the program segment char line [80]; scanf ( %[^\n],line); printf( %s,line); will read a line of input from the keyboard and display the same on the screen. We would very rarely use this method. Using getchar and gets Functions To read a single character from the terminal, using the function getchar. We can use this function repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array. The reading is terminated when the newline character ( \n ) is netered and the null character is then inserted at the end of the string. The getchar function call takes the form: char ch; ch = getchar ( ); Note that the getchar function has no parameters. 181 #include <stdio.h> void main() char line[81], character; int c; c = 0; printf("enter text. Press <Return> at end\n"); do character = getchar( ); line[c] = character; c++; while(character!= '\n'); c = c - 1; line [c] = '\0'; printf("\n%s\n", line); 182 getchar and gets Conti. Another and more convenient method of reading a string of text containing white spaces is to use the library function gets available in the <stdio.h> header file. This is a simple function with one string parameter and called as under. gets (str); str is string variable declared properly. It reads characters into str from the keyboard until a new line character is encountered and then appends a null character to the string. Unlike scanf, it does not skip white spaces. For example the code segment char line [80]; gets (line); printf( %s,, line); reads a line of text fromthe keyboard and displays it on the screen. The last two statements may be combined as follows: printf( %s,gets(line)); C does not provide operators that work on strings directly. For instance we cannot assign one string to another directly. For example, the assignment statements. string = ABC string1 = string2; are not valid. #include<stdio.h> void main() char string1[80],string2[80]; int i; printf("enter a string \n"); printf("?"); scanf("%s",string2); for(i=0;string2[i]!= '\o'; i++) string1[i] = string2[i]; string1[i] = '\o'; printf("\n"); printf("%s\n", string1); printf("number of characters = %d\n",i); 183 184 46

WRITING A STRINGS TO SCREEN We have used extensively the printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character. For example, the statement printf( %s, name); can be used to display the entire contents of the array name. We can also specify the precision with which the array is displayed. For instance, the specification %10.4 Indicates that the first four characters are to be printed in a field width of 10 columns. However, if we include the minus sign in the specification (e.g., %-10.4s), the string will be printed leftjustified. Using putchar and puts Functions Like getchar, C supports another character handling function putchar to output the values of character variables. It takes the following form: char ch = A ; putchar (ch); The function putchar requires one parameter. This statement is equivalent to: printf( %c,ch); We have used putchar function to write characters to the screen. We can use this function repeatedly to output a string of characters stored in an array using a loop: 185 Using putchar and puts Functions Conti Example: char name[6] = PARIS ; for(i=0;i<5;i++) putchar (name[i]); putchar( \n ); Another and more convenient way of printing string values is to use the function puts declared in the header file <stdio.h>. This is a one parameter function and invoked as under: puts (str); Where str is a string variable containing a string value. This prints the value of the string variable str and then moves the cursor to the beginning of the next line on the screen. For example, the program segment char line [80]; gets (line); puts (line); Reads a line of text from the keyboard and displays it on the screen. Note that the syntax is very simple compared to using the scanf and printf statements 186 STRING HANDLING FUNCTIONS The C Library supports a large number of string handling function that can be used to carry out many of the string manipulations. The most commonly used string handling functions. Function strcat ( ) strcmp ( ) strcpy ( ) strlen ( ) Action Concatenates two strings Compares two strings Copies one strings over another Finds the length of a string Function 187 188 47

C function can be classified into two categories, namely, library functions and user defined functions. main is an example of user defined functions. printf and scanf belong to the category of library functions.wehave also used otherlibraryfunctionssuchas sqrt, cos, strcat, etc. The main distinction between these two categories is that library functions are not required to be written by us whereas a user defined function has to be developed by the user at the time of writing a program. Some Characteristic of modular programming are: 1. Each module should do only one thing. Introduction 2. Communication between modules is allowed only by a calling module. 3. A module can be called by one and only one higher module 4. No communication can take place directly between modules that do not have calling called relationship 5. All modules are designed as single entry, single exit systems using control structures Need for User Defined Functions 1. Every program must have a main function to indicate where the program has to begin its execution. While it is possible to code any program utilizing only main function. It leads to a number of problems. 2. The program may become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult. 3. If a program is divided into functional parts, then each part m ay be independently coded and later combined into a single unit. These subprograms called functions are much easier to understand, debug, and test. 4. The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited. 5. It us easy to locate and isolate a faulty function for further investigations. 6. A function may be used by many other programs. 189 190 DEFINITION A function is a named, independent section of C code that performs a specific task and optionally returns a value to the calling program. A function is named A function is independent. Function COND FUNCTION DECLARATION FUNCTION DEFINITION FUNCTION INVOCATION (FUNCTION CALL) A function performs a specific task. A function can return a value to the calling program. 191 192 48

FUNCTION DEFINITION SYNTAX A function definition, also known as function implementation shall include the following elements. 1. Function Name 2. Function Type 3. List of Parameters 4. Local variable declarations 5. Function Statements 6. A Return statement All the six elements are grouped into two parts, namely, 1. Function header (First three Elements) 2. Function Body (Second three Elements) function_type function_name(parameter_list) local variable declaration; executable statement_1; executable statement_2; --------------------------------- --------------------------------- return statement; Example: float mul ( float x, float y) float result; result = x * y; return (result); 193 FUNCTION PROTYPING OR FUNCTION DECLARATION A function prototype is a very important feature of modern C programming It must be added to a C program just before the main function, if we call that function before defining it It tells the compiler what type of value the function returns, numbers and types of parameters, and order in which these parameters are expected. There is no need for a prototype if the function is called after its definition 194 FUNCTION DECLARATION SYNTAX Like variables, all functions in a C program must be declared, before they are invoked, A function declaration (also known as function prototype) consists of four parts. 1. Function type (return type) 2. Function name 3. Parameter list 4. Terminating semicolon The general format is Function_type function_name(parameter_list); Example: float mul (float x, float y); Function Definition A simple format of a C function definition is as follows: return-value-type functionname(parameters) Declarations; Statements; Return (expression); Function Prototype 195 196 49