2.6k likes | 2.61k Views
Chapter 1 Overview of “C” The root of all modern programming language is ALGO, it is introduced in 1960. ALGO gave the new concept of the structure programming. Subsequently varies languages are announced.
E N D
Chapter 1 Overview of “C” • The root of all modern programming language is ALGO, it is introduced in 1960. ALGO gave the new concept of the structure programming. Subsequently varies languages are announced. • In 1967 Martin Richards developed a language called BCPL( Basic Combined Programming Language) . • In 1970, Ken Thompson created a language using many features of BCPL and it simply called B language. Both BCPL and B was “type less” system programming language. • C language was developed by Dennis Ritchie at the Bell Laboratories in 1972. C language uses many features of the ALGO, BCPL and B Languages. It also added new concepts of the “data type” and many powerful features. Unix operating system is totally coded in C language.
In 1983 American National Standard Institute (ANSI) appoint a technical committee to define a standard of C. • The committee approved a version of c in December 1989 which is now known as ANSI C • It was the approved by the International Standards Organization (ISO) in 1990.This version of the c is also referred as C89 Importance of the C language: • It is Robust Language. It’s rich set of bit in function and operator can be used to write any complex program. • The C Compiler combines the features of the assembly language and high level language so it is suitable for both system software and business package.
Programs written in C languages are very efficient and fast because of its variety of data types and powerful operators. • There are several inbuilt functions which is used to build any program. • There are 32 keywords in C Which is used to make the program. • C is highly portable language. • C language is suitable for structure programming. This modular structure makes program debugging, testing and maintenance easier. • The ability to extend itself. It means we can add our own functions into the c library
Sample Program for C language to print hello. /* Write the Program to Print the Hello */ #include<stdio.h> #include<conio.h> void main() { clrscr(); printf (“Hello world”); getch(); } Alt + f9 -> To compile the program Ctrl + f9 -> To run the program
Documentation Section Link Section Definition Section Global Declaration Section Main () Function Section { Declaration Part Executable Part } Sub Program Section Function 1 Function 2 etc.. Basic Structure of the c program:
Executing a C Program : • Executing a Program C Involves a Series of Steps : • Creating a Program • Compile the Program • Linking the Program with functions that are needed from the C library • Executing the Program
Enter the Program Code Compile Program with Compiler Edit the Source Program Syntax Error Yes Object Code No Link with System Library Executable Object Code Execute Object Code Generate the Output
Chapter : 2 Constants, Variable and Data Types Introduction :- The Sequence of the Instruction written to perform specific task is called the Program. This Instructions are formed using special symbols and words according to some rigid rule is known as syntax rules. Every Instruction must be written according to the syntax rule of the languages. Like any other languages C languages has its vocabulary and grammar. They are follow up for making the program. In this Chapter we will discuss about various constants, variables and data types are used in C Programming.
Character Set : • Character Set is the set of the character. • This characters are used to form the word, numbers and expression. • The characters in the c are grouped into the following categories. Letters Digits Special characters White Spaces. Letters : Uppercase A…Z, Lowercase a…z Digits : All decimal digits 0 to 9 Special Character : ,(comma) .(period) ; (semicolon) : (colon), & (ampersand), # (number sign) etc. White spaces : Blank Space, Horizontal Space, New Line.
Trigraph Characters: • Many Non – English Keywords don’t support all the characters mentioned in character set. • ANSI C Introduce the concept “trigraph” Sequences to enter special character that are not available on some keyboard. • Each trigraph sequence consists of three characters (two question mark followed by a character) Trigraph SequenceTranslation ??= # nubersign ??( [ left bracket ??) ] right bracket ??< { left braces ??> } Right braces
C Tokens: Smallest Individual units are known as C Tokens. There are six types of the C Tokens. • Keywords • Identifiers • Constants • String • Special Symbols • Operators. Keywords: • Every C word is classified as either keyword or identifier. • All keywords have fixed meanings and you can not change its meanings. • Keywords serve as a basic building blocks for program statement. ANSI C supports 32 keywords that are listed in ANSI C book.
Ex: int, float, double, extern, static, auto, continue, if, goto short, long etc. are the keywords Identifiers: • Identifiers refer to the names of variables, functions and arrays. • These are user defined names and consists of sequence of letters and digits. • Both uppercase and lowercase letters are permitted to make the identified but generally lowercase letters are used to make the variable. Rules for Identifiers: • First character must be alphabet • Must not contain white space • Only first 31 characters are significant • Can not use keyword as a identifier
Constants: Constants referred as a fixed value that don't change during the execution of the program. C Support Several types of constants: Constants Numeric Constants Integer constants Real Constants Character Constants Single Character Constants String Constants
Integer Constants: An integer constants refers as a sequence of digits. There are three types of integer constants. • Decimal Integer • Octal Integer • Hexadecimal Decimal Integer : It consists of 0-9 digits, preceded by an optional – or + sign. Valid example of decimal integer are : 123 , -321, 0 , 654321, +78 Embedded spaces, comma and non digit characters are not permitted between digits. 15 750, 20,000, $1000 are Illegal
Octal Integer: An Octal Integers consists of digits 0-7 with a leading 0. Ex: 037, 0, 0435, 0551 Hexadecimal Integer: A sequence of digits preceded by 0x or OX is considered as Hexadecimal Integer. Hexadecimal Integer includes 0 to 9 digits and A to F letters. Ex: 0x9, 0x9F, OXbcd etc are valid. Real Constants: Integer numbers are inadequate to represent quantities such as distance, heights, temperature, price and so on. These quantities are represented by a number containing fractional parts like 12.32. Such numbers are called real constants
These numbers having a whole number followed by a decimal digits. ex: 0.85, -0.75, 85.45, +241.54 It is possible to omit the digit before the decimal digit and after the decimal digit. ex: 215., .23 , -.71 , +54. A real number may also be expressed in exponential (Scientific) notation. General form : mantissa e exponent The mantissa is either a real number or integer number. Exponent is an integer number with + or – sign. The letter e separating mantissa and exponent can be written either in lowercase or in uppercase letter.
ex : 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiple by 102 75000 written as 7.5E4 or 7.5E+4 -0.00038 written as -3.8e-4 Comma, White space and dollar space is not permitted in digits. 25,0.000 , 7.1 e 4 , 1.5 E 2.5 (exponent must be an integer), $255. Single character constants: A single character constant contains a single character enclosed with a pair of single quotation mark (‘ ’). ex: ‘5’, ‘x’, ‘;’ , ‘ ’ Note that character constant ‘5’ is not same as number 5. character constant have a integer value known as ASCII value
ex : printf (“%d”, ‘a’) would print the number 97. printf(“%c”, ‘97’) would print the letter a. String Constants : A String Constant is a sequence of characters enclosed in double quotation mark. ex: “Hello” , “1987”, “Well Done”, “X” Note : A single String constant does not have an equivalent integer value, while a character constant has an equivalent integer value. Backslash character constant: Backslash character constant are used in output function. ex: ‘\n’ – new line, ‘\t’ – horizontal tab, ‘\’’-single quote etc.
VARIABLE : A variable is a data name that may be used to store a data value. Unlike constants that remain unchanged during the execution of the program, a variable may take different value at different time. Rules to declare a variable : • They must begin with letter • variable length must be 31 character significant. • Both lowercase and uppercase letters are distinct. ex Total and total are not same • It should not be a keyword • White space, Dollar sign are not allowed. ex: John, delhi, First_tag, int_type ---- valid Price$, char, group one, 123, 25th, (area) ------- Invalid
Declaration of Variable: Syntax : data_type v1,v2,v3….vn ; where v1,v2..vn are different variable name. Ex: int count; int number, total; double ratio; float price; char c; where int, double, float and char are data type. Assign Value to a Variable : Assignment operator (=) is used to assign value to a variable. Ex: price = 12.50; ratio = 12.2345; number=12; c=‘a’;
Data Types: C language is rich in its data types: ANSI C support three classes of data types. 1. Primary Data Type 2. Derived Data Type 3. User-Defined Data Type.
Integral Type Integer Character Signed int short int Long int Unsigned unsigned int unsigned short int unsigned Long int char signed char unsigned char Floating Point Type void float double long double Primary Data Type :
All C compiler support five fundamental data types, namely integer(int), character(char), floating point(float), double-precision floating point(double) and void. Integer types: • Integers are whole numbers with a range of values supported by a particular machine. • There are signed integer and unsigned integer. Signed integer uses one bit for sign and 15 bits for magnitude of the number. Unsigned integers are always positive. It does not contain any bit for sign so that it occupies all the bit for the magnitude of the number. (Note : For 16 bit machine) • By using equation -2n to +2n-1 we can find out the range of the number. Where n is the number of bits.
To provide some control over the range of number and storage space, C has three classes of integer storage, namely short int, int and long int in both signed and unsigned forms. Size and Range of Data Type on a 16-bit machine. Type size(bits) Range int or signed int 16 -215 to 215 -1 unsigned int 16 0 to 216-1 short int or 8 -27 to 27 -1 signed short int unsigned short int 8 0 to 28 -1 long int or 32 -231 to 231 -1 signed long int unsigned long int 32 0 to 232 -1
Floating Point Types: • Floating point numbers are stored in 32 bits (on all 16bit and 32 bit machines) with 6 digits of precision. • Floating point numbers are defined in C by the keyword float. • When the accuracy provided by float is not sufficient double data type is used. It uses 64 bits giving a precision of 14 digits. • When you want to extend more precision you can use the long double data type. it uses 80 bits Type size(bits) Range float 32 3.4E-38 to 3.4E+38 double 64 1.7E-308 to 1.7E+308 long double 80 3.4E-4932 to 1.1E+4932
Void Types : • Void type has no values. • Void type does not return any values. Character Type: • Character type data type is char. • It’s storage is 8bit to store a bit. • The qulifier signed and unsigned explicitly applied on character type Type size (bits) range char or signed char 8 -27 to 27 -1 unsigned char 8 0 to 28 -1
Note : Integer constants by default represent int data type. We can override this default by specifying unsigned or long after the number (by appending U or L). ex: Literal Type value +111 int 111 -222 int 222 45678U unsigned int 45,678 -56789L long int 56,789 987654UL unsigned long int 9,87,654 similarly floating point constants by default it will take double data type. To override we must append f or F for float type and l or L for long double type. ex: Literal Type value 1.234 double 1.234 -1.2f float -1.2 1.23456789L long double 1.23456789
/* Program To Show the declaration, assignments and values stored in varies types of variables */ #include<stdio.h> #include<conio.h> void main() { float x; double q ; unsigned k ; int m =5431; long int n = 1234567890; x=1.234567890000; q= 1.0 ; k=54321; printf(“%d”, m); printf(“%ld\n”, n); printf(“%f\n”, x); printf(“%lf”,x); printf(“%lf\n”,q); printf(“%u”,k); }
Defining Symbolic Constants: Those constants which are repeatedly used in the programs are defined as a symbolic constants. Because of Symbolic constants we can solve problems like: • Problem in modification of the program • Problem in understanding the program Syntax: #define symbolic_name value_of_constant Ex: #define PI 3.14 #define MAX 200 #define PASS_MARK 50
Rules to define the symbolic constants: • Symbolic names are written in Capital letters to visually distinguish them from the normal variables. • No blank space between the pound sign ‘#’ and the word define is permitted. • ‘#’ must be the first character in the line. • A blank space is required between #define and symbolic name. • #define statement must not end with a semicolon • Assignment operator is not used to assign a value to the symbolic name. • A statement can define only one name Invalid define statement: #define X=2.5, # define MAX 10, #define N 25; , #define PI , R 3.14 , #define PRICE$ 100
Declaring a variable as constant: Syntax: const data_type variable_name = value ; Ex: const int class_size=40; Using const keyword we can made any variable’s value constant and because of that we cant change the value of that variable during the execution time. Declaring a variable as volatile: Qualifier volatile that could be used to tell explicitly the compiler that a variable’s value may be changed at any time by some external source. Syntax: volatile int date.
User-Defined Type Declaration: • Using typedef keyword we can define our own user defined data type. Syntax: typedef type identifier; Ex: typedef int marks; marks sub1,sub2; • Another user defined data type is enum (enumeration) which can be used to declare variable that can have one of the values enclosed within the braces (Known as enumeration constants) • The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants.
Syntax: enum identifier {value1, value2, value3,….,valueN}; Example: enum day {Monday, Tuesday,……..,Sunday}; enum day week_st, week_end; week_st = Monday; week_end = Friday; If(week_st == Tuesday) week_end = Saturday; • enum day {Monday=1,Tuesday,….., Sunday}; Here Monday = 1 constant value so the remaining constants are assigned value that increase successively by 1. • Declaration combined as follow: enum day {Monday,…..,Sunday} week_st, week_end;
Read data from keyboard: Using Scanf function we can read data from the keyboard. Syntax: scanf(“control string”,&variable1,&variable2);.
Chapter 3 Operators and Expression C support a rich set of built in operator. • An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. C operators are classified into following categories: • Arithmetic operator • Relational operator • Logical operator • Assignment operator • Increment and Decrement operator • Conditional operator • Bitwise operator • Special operator.
Arithmetic operator: +(Addition), -(Subtraction), *(Multiplication), /(Division) , %(Modulat Division). All this are arithmetic operators. ex: a-b a+b a*b a/b a%b -a*b Here a and b are variables and are known as operands. Note : Modular operator can not be used in the floating point operation. Arithmetic operator has three types: (1) Integer Arithmetic (2) Real Arithmetic (3) Mixed mode Arithmetic
Integer Arithmeic: When both the operands in a arithmetic expressions are integer, the expression is called an integer expression, and the operation is called integer arithmetic. If a and b both are integer than for a=14 and b=4 we have following results: a – b = 10 a + b = 18 a * b = 56 a / b = 3 (Decimal part truncated) a % b = 2 (remainder of division) During integer division,if both the operands are of the same sign,the result is truncated towards the zero. If one of them is negative, the direction of truncation is implementation dependent. That is, 6/7 = 0 and -6/-7 = 0
Similarly during modular division, the sign of the result is always the sign of the first operand (dividend). That is -14%3 = -2 -14%-3 = -2 14%-3 = 2 Ex : /* Program to convert a given number of days into months and days*/ main() { int month, day; clrscr(); scanf(“%d”,&day); month = day/30; day = day%30; printf(“Month = %d Days = %d”, month,day); getch(); }
Real Arithmetic : An arithmetic expression involving only real operands is called real arithmetic. A real operands may assume values either in decimal or exponential notation. If x,y,z are floats, then we will have: x = 6.0/7.0 = 0.85713 y = -2.0/3.0 = -0.666667 the operator % can not be used with real operands. Mixed Mode Arithmetic: When one of the operand is real and the other is integer, the expression is called the mixed mode arithmetic expression. If either operand is real type then only real operation is performed and the result is always a real number. Thus 15/ 10.0 = 1.5 where as 15/10 = 1
Relational operators: Whenever you want to compare two entities at that time you can use the Relational operator. An expression containing a relational operator is known as relational expression. C Support six type of the relational operators: operator Meaning < less than <= is less than or equal to > greater than >= is greater than or equal to == is equal to != is not equal to Relational operators are generally used in the decision making statements like if and while and it returns value true and false
Ex: 4.5 <= 10 true a+b == c+d true if equal else false 10< 7+5 true -35 >= 0 false Logical Operators: Logical operators are generally used when you want to test more than one condition. There are three types of the logical operator: Logical And && Logical Or || Logical Not ! Ax expression of this kind, which combines two or more relational expressions, is termed as a logical expression or a compound relational expression.
Truth Table: Op-1 Op-2 value of the expression op-1 && op-2 op1 || op2 1 1 1 1 1 0 0 1 0 1 0 1 0 0 0 0 Example : if(age > 55 && salary < 1000) if(number < 0 || number > 100) Assignment Operators: Assignment operators are used to assign the result of an expression to a variable. We have seen the usual assignment operator ‘=’. In addition c has a ‘shorthand’ assignment operators of the form.
Syntax: v op = exp Where v is a variable, exp is an expression and op is a c binary arithmetic operator. Is equivalent to : V = v op (exp) Ex: x+=1 is equivalent to x= x+1 Statement with simple Statement with shorthand Assignment operator operator. a=a+1 a+=1 a=a-1 a-=1 a=a*(n+1) a*=n+1 Use of the shorthand assignment operator: • Left hand side need not to be repeated so easier to write • Statement is easier to read • Statement is more efficient.
Increment(++) and Decrement(--) Operator: ++ operator add 1 to the operand, while –- subtracts 1. Both are unary operator and takes the both form. ++m or m++ --m or m-- We generally used this statement in the for and while loop. ++m and m++ both are different thing when they are used in the expression. For m=5; Y= ++m In this case value of y and m would be 6 Y= m++ In this case vale of y would be 5 and m would be 6. Increment and decrement statement is used in the complex statement: M= n++ -j +10 but old value of the n is incremented after the evaluation of the equation
#include<stdio.h> #include<conio.h> void main() { int n,k,m; clrscr(); k=1,m=2; n= k++ + m; printf("%d",k); printf("%d",n); getch(); } Output:k=2, n=3
Conditional operator: Conditional operator is also called the “ternary operator”. Syntax: exp1 ? exp2 : exp3 Ex: a = 10; b = 15; X = (a>b) ? a : b; Its same as if (a > b) x = a; else x = b;
Bitwise Operator : • Whenever you want to manipulate your data at that time you can use the Bitwise operator. • These operators are generally used to testing the Bits, or shifting them left or right. • Bitwise operator can not be applied to float or double. • List of the Bitwise operators and their meanings are as follow. Operator Meaning & bitwise AND | bitwise OR ^ bitwise exclusive OR << shift left >> shift right
Special Operator : • C Support some special operator like comma, and sizeof operator. Comma Operator : Comma Operator can be used to link the related expression together. Ex: Value = (x=10, y=5, x+y); In for loop. A list of expressions are evaluated from left to right direction. Ex: for(n=1,n<=10;n++); The sizeof Operator: Sizeof operator is a compile time operator. It returns number of bytes occupied by the operand. The operand may be a variable, constant or a data type.
Ex: m = sizeof(sum); n = sizeof(long int);
#include<stdio.h> #include<conio.h> void main() { int a,b,c,d; clrscr(); a=15, b= 10; c= ++a - b; // value of a is increamented before use in expression printf("a=%d b=%d c=%d\n", a,b,c); d= b++ + a; // value of b is increament after use in expression printf("\na = %d b = %d d = %d",a,b,d); printf("\n a/b = %d",a/b); printf("\n a%b = %d",a%b); printf("\n a*=b = %d", a*=b); printf("%d\n", (c>d) ? 1:0); printf(“%d”,sizeof(int)); getch(); } Output : a=16 b=10 c=6 a = 16 b = 11 d = 26 a/b = 1 a%b = 5 a*=b = 176 0 2